Is it possible to assign the same value to multiple keys in a dict object at once?


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?


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

This is, of course, will return first encountered value, key for which contains given element.

Answered By – SilentGhost

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published