Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create Dictionary with Variable Name Values

am trying to figure out how to best create a python dictionary where the values are variable names

e.x.

ruleLst = ["gender+brand","sport+gender","sport+gender+brand"]

for i in ruleLst:
    
    new_values = i.split("+")
    rules.update({i:new_values})

rules

returns:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
 'gender+brand': ['gender', 'brand'],
 'sport+gender': ['sport', 'gender'],
 'sport+gender+brand': ['sport', 'gender', 'brand']
}

What I try to output is:

{
 'gender+brand': [gender, brand],
 'sport+gender': [sport, gender],
 'sport+gender+brand': [sport, gender, brand]
}

where gender, brand, sport are lists define in the code before ruleLst is define

Thanks in advance

>Solution :

You can use list comprehension like:

ruleLst = ["gender+brand","sport+gender","sport+gender+brand"]
gender = ["M", "F"]
sport = ["basket", "volleyball"]
brand = [1, 2]
a = {i: [globals()[j] for j in i.split("+")] for i in ruleLst}
print(a)

and output:

{
'gender+brand': [['M', 'F'], [1, 2]],
'sport+gender': [['basket', 'volleyball'], ['M', 'F']],
'sport+gender+brand': [['basket', 'volleyball'], ['M', 'F'], [1, 2]]
}

Reference:

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading