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)
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.
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.
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().
for i in ('apple', 'banana', 'carrot'): fruitdict[i] = locals()[i]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With