Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python variables as keys to dict

Is there an easier way to do this in Python (2.7)?: Note: This isn't anything fancy, like putting all local variables into a dictionary. Just the ones I specify in a list.

apple = 1 banana = 'f' carrot = 3 fruitdict = {}  # I want to set the key equal to variable name, and value equal to variable value # is there a more Pythonic way to get {'apple': 1, 'banana': 'f', 'carrot': 3}?  for x in [apple, banana, carrot]:     fruitdict[x] = x # (Won't work) 
like image 508
atp Avatar asked Oct 19 '10 21:10

atp


People also ask

How do you convert a variable to a dictionary in Python?

To convert Python Set to Dictionary, use the fromkeys() method. The fromkeys() is an inbuilt function that creates a new dictionary from the given items with a value provided by the user. Dictionary has a key-value data structure. So if we pass the keys as Set values, then we need to pass values on our own.

Can I use variables in dictionary Python?

Anything which can be stored in a Python variable can be stored in a dictionary value. That includes mutable types including list and even dict — meaning you can nest dictionaries inside on another. In contrast keys must be hashable and immutable — the object hash must not change once calculated.

How do you use a key as a variable in Python dictionary?

E.g., if you do items = locals(); id(locals()) == id(items) you would get equality. Or if you did items=locals(); b = 3 ; items['b'] it will find the new variable b, since it didn't actually copy the locals dict to items (which would be slower). If you had done items=locals().


1 Answers

for i in ('apple', 'banana', 'carrot'):     fruitdict[i] = locals()[i] 
like image 137
dr jimbob Avatar answered Oct 06 '22 06:10

dr jimbob