Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a dictionary with same values [duplicate]

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?

like image 957
NIlesh Sharma Avatar asked Aug 15 '12 21:08

NIlesh Sharma


People also ask

Can a dictionary have duplicate values?

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.

Can you have the same key twice in a dictionary?

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.

Can you have the same key twice in a dictionary python?

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.


2 Answers

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}
like image 53
Valdir Stumm Junior Avatar answered Sep 26 '22 19:09

Valdir Stumm Junior


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}
like image 20
BorrajaX Avatar answered Sep 26 '22 19:09

BorrajaX