Suppose I have dictionary a = {}
and I want to have it a result like this
value = 12
a = {'a':value,'b':value,'f':value,'h':value,'p':value}
and so on for many keys:same value
. Now of course I can do it like this
a.update({'a':value})
a.update({'b':value})
and so on.... but since the value is same for all the keys, don't we have a more pythonic approach to do this?
Duplicate keys are not allowed. A dictionary maps each key to a corresponding value, so it doesn't make sense to map a particular key more than once. If you specify a key a second time during the initial creation of a dictionary, then the second occurrence will override the first.
No, each key in a dictionary should be unique. You can't have two keys with the same value. Attempting to use the same key again will just overwrite the previous value stored. If a key needs to store multiple values, then the value associated with the key should be a list or another dictionary.
Dictionaries do not support duplicate keys. However, more than one value can correspond to a single key using a list. For example, with the dictionary {"a": [1, 2]} , 1 and 2 are both connected to the key "a" and can be accessed individually.
You could use dict comprehensions (python 2.7+):
>>> v = 12
>>> d = {k:v for k in 'abfhp'}
>>> print d
{'a': 12, 'h': 12, 'b': 12, 'p': 12, 'f': 12}
How about creating a new dictionary with the keys that you want and a default value?. Check the fromkeys method.
>>> value=12
>>> a=dict.fromkeys(['a', 'b', 'f', 'h', 'p'], value)
>>> print a
{'a': 12, 'h': 12, 'b': 12, 'p': 12, 'f': 12}
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