Reputation: 1314
I'm searching for an elegant more generic way to fill a dictionary with variables:
dic = {}
fruit = 'apple'
vegetable = 'potato'
dic['fruit'] = fruit
dic['vegetable'] = vegetable
is there a more generic way without using the variable-name in quotes ?
Upvotes: 1
Views: 1377
Reputation: 34028
If the quotes are the problem, how about this?
fruit = 'apple'
vegetable = 'potato'
dic = dict(
fruit = fruit,
vegetable = vegetable
)
Upvotes: 4
Reputation: 2297
May not be a very elegant solution but you could use locals()
for retrieving the variables and then convert them into a dictionary.
fruit = 'apple'
vegetable = 'potato'
dic = {key:value for key, value in locals().items() if not key.startswith('__')}
This results in {'vegetable': 'potato', 'fruit': 'apple'}
However, I believe a better option would be to pass the variable names and create a dictionary as provided in this answer:
def create_dict(*args):
return dict({i:eval(i) for i in args})
dic = create_dict('fruit', 'vegetable')
Edit: Using eval()
is dangerous. Please refer to this answer for more information.
Upvotes: 1