一次可以在一个dict对象中为多个键分配相同的值吗? [英] Is it possible to assign the same value to multiple keys in a dict object at once?
问题描述
在Python中,我需要一个字典对象,如下所示:
In Python, I need a dictionary object which looks like:
{'a': 10, 'b': 20, 'c': 10, 'd': 10, 'e': 20}
通过将 dict.update()
和 dict.fromkeys()
的功能相结合,所以:
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', 'b', 'c'], 10))
myDict.update(dict.fromkeys(['b', 'e'], 20))
然而,由于代码正在为新手可能需要随时添加键/值的用户编写,所以我更喜欢一个简单的裸机(Perl-like)语法如:
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
,给我:
myDict = {('a', 'c', 'd'): 10, ('b', 'e'): 20}
有没有办法简化我的第一个例子(使用 dict.update()
和 dict.fromkeys()
)进一步,并获得我正在寻找的dict对象?
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?
或者,如果我在第二个例子中有一个含有元组的dict,是否有一个简单的方法对于我来执行查找,例如 myDict ['c']
或 myDict.get('c')
和得到值10?
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', '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.
这篇关于一次可以在一个dict对象中为多个键分配相同的值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!