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

前端 未结 6 1900
时光取名叫无心
时光取名叫无心 2020-11-27 03:44

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 th

6条回答
  •  被撕碎了的回忆
    2020-11-27 04:17

    I would say what you have is very simple, you could slightly improve it to be:

    my_dict = dict.fromkeys(['a', 'b', 'c'], 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.

提交回复
热议问题