Create Dictionary with Variable Name Values

402 views Asked by At

I 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:

{
 '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 defined in the code before ruleLst is defined.

3

There are 3 answers

3
kingkong On BEST ANSWER

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:

0
Paul Kocian On

Try using globals()[new_values[0]] and globals()[new_values[1]] instead of new_values to get the variables value.
Like this:

ruleLst = ["gender+brand","sport+gender","sport+gender+brand"]
rules = {}
gender = ["male", "female"]
sport = ["basket", "volleyball"]
brand = ["x", "y"]

for i in ruleLst:
    
    new_values = i.split("+")
    rules.update({i:[globals()[new_values[0]], globals()[new_values[1]]]})

print(rules)
0
Jesper On

You could solve this with the map function like this. By casting it as a dict you'll get the dictonary you want.

rules = dict(map(lambda elem: [elem, elem.split('+')], ruleLst))