In Python, I need a dictionary object which looks like:
{'a': 10, 'b': 20, 'c': 10, 'd': 10, 'e': 20}
I've been able to get this successfully by combining the dict.update()
and dict.fromkeys()
functions like so:
myDict = {} myDict.update(dict.fromkeys(['a', 'c', 'd'], 10)) myDict.update(dict.fromkeys(['b', 'e'], 20))
However, because the code is being written for novice users who may need to make add keys/values on occasion, I'd prefer a simple bare-bones (Perl-like) syntax such as:
myDict = {} myDict['a', 'c', 'd'] = 10 myDict['b', 'e'] = 20
This, however, gives me:
myDict = {('a', 'c', 'd'): 10, ('b', 'e'): 20}
Is there a way I can simplify my first example (using dict.update()
and dict.fromkeys()
) further, and get the dict object I'm looking for?
Or, alternatively, if I have a dict with tuples as in my second example, is there an easy way for me to do a lookup such as myDict['c']
or myDict.get('c')
and get the value 10?
Answer. 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.
In Python dictionary, if you want to display multiple keys with the same value then you have to use the concept of for loop and list comprehension method. Here we create a list and assign them a value 2 which means the keys will display the same name two times.
Keys in a dictionary can only be used once. If it is used more than once, as you saw earlier, it'll simply replace the value.
In Python, we can add multiple key-value pairs to an existing dictionary. This is achieved by using the update() method. This method takes an argument of type dict or any iterable that has the length of two - like ((key1, value1),) , and updates the dictionary with new key-value pairs.
I would say what you have is very simple, you could slightly improve it to be:
my_dict = dict.fromkeys(['a', 'c', 'd'], 10) my_dict.update(dict.fromkeys(['b', 'e'], 20))
If your keys are tuple you could do:
>>> my_dict = {('a', 'c', 'd'): 10, ('b', 'e'): 20} >>> next(v for k, v in my_dict.items() if 'c' in k) # use .iteritems() python-2.x 10
This is, of course, will return first encountered value, key for which contains given element.
Similar to @SilentGhost but a more declarative syntax (with Python 3.5+) I prefer:
myDict = { **dict.fromkeys(['a', 'c', 'd'], 10), **dict.fromkeys(['b', 'e'], 20) }
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