Python字典理解
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14507591/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python Dictionary Comprehension
提问by Rushy Panchal
Is it possible to create a dictionary comprehension in Python (for the keys)?
是否可以在 Python 中创建字典理解(对于键)?
Without list comprehensions, you can use something like this:
如果没有列表推导式,您可以使用以下内容:
l = []
for n in range(1, 11):
l.append(n)
We can shorten this to a list comprehension: l = [n for n in range(1, 11)].
我们可以缩短这一个列表理解:l = [n for n in range(1, 11)]。
However, say I want to set a dictionary's keys to the same value. I can do:
但是,假设我想将字典的键设置为相同的值。我可以:
d = {}
for n in range(1, 11):
d[n] = True # same value for each
I've tried this:
我试过这个:
d = {}
d[i for i in range(1, 11)] = True
However, I get a SyntaxErroron the for.
但是,我SyntaxError在for.
In addition (I don't need this part, but just wondering), can you set a dictionary's keys to a bunch of different values, like this:
另外(我不需要这部分,只是想知道),您能否将字典的键设置为一堆不同的值,如下所示:
d = {}
for n in range(1, 11):
d[n] = n
Is this possible with a dictionary comprehension?
这可能与字典理解有关吗?
d = {}
d[i for i in range(1, 11)] = [x for x in range(1, 11)]
This also raises a SyntaxErroron the for.
这也引发了SyntaxError对for.
采纳答案by BrenBarn
There are dictionary comprehensions in Python 2.7+, but they don't work quite the way you're trying. Like a list comprehension, they create a newdictionary; you can't use them to add keys to an existing dictionary. Also, you have to specify the keys and values, although of course you can specify a dummy value if you like.
Python 2.7+ 中有字典推导式,但它们的工作方式与您尝试的方式不同。就像列表理解一样,他们创建了一个新字典;您不能使用它们向现有字典添加键。此外,您必须指定键和值,当然您也可以根据需要指定一个虚拟值。
>>> d = {n: n**2 for n in range(5)}
>>> print d
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
If you want to set them all to True:
如果要将它们全部设置为 True:
>>> d = {n: True for n in range(5)}
>>> print d
{0: True, 1: True, 2: True, 3: True, 4: True}
What you seem to be asking for is a way to set multiple keys at once on an existing dictionary. There's no direct shortcut for that. You can either loop like you already showed, or you could use a dictionary comprehension to create a new dict with the new values, and then do oldDict.update(newDict)to merge the new values into the old dict.
您似乎要求的是一种在现有字典上一次设置多个键的方法。对此没有直接的捷径。你可以像你已经展示的那样循环,或者你可以使用字典理解来创建一个带有新值的新字典,然后oldDict.update(newDict)将新值合并到旧字典中。
回答by mgilson
You can use the dict.fromkeysclass method ...
您可以使用dict.fromkeys类方法...
>>> dict.fromkeys(range(5), True)
{0: True, 1: True, 2: True, 3: True, 4: True}
This is the fastest way to create a dictionary where all the keys map to the same value.
这是创建字典的最快方法,其中所有键都映射到相同的值。
But do notuse this with mutable objects:
但是千万不能用可变对象使用:
d = dict.fromkeys(range(5), [])
# {0: [], 1: [], 2: [], 3: [], 4: []}
d[1].append(2)
# {0: [2], 1: [2], 2: [2], 3: [2], 4: [2]} !!!
If you don't actually needto initialize all the keys, a defaultdictmight be useful as well:
如果您实际上不需要初始化所有键,adefaultdict也可能有用:
from collections import defaultdict
d = defaultdict(True)
To answer the second part, a dict-comprehension is just what you need:
要回答第二部分,字典理解正是您所需要的:
{k: k for k in range(10)}
You probably shouldn't do this but you could also create a subclass of dictwhich works somewhat like a defaultdictif you override __missing__:
你可能不应该这样做,但你也可以创建一个子类,如果你重写dict它,它的工作方式有点像 a :defaultdict__missing__
>>> class KeyDict(dict):
... def __missing__(self, key):
... #self[key] = key # Maybe add this also?
... return key
...
>>> d = KeyDict()
>>> d[1]
1
>>> d[2]
2
>>> d[3]
3
>>> print(d)
{}
回答by NPE
>>> {i:i for i in range(1, 11)}
{1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, 10: 10}
回答by Bryan
Use dict() on a list of tuples, this solution will allow you to have arbitrary values in each list, so long as they are the same length
在元组列表上使用 dict(),此解决方案将允许您在每个列表中使用任意值,只要它们的长度相同
i_s = range(1, 11)
x_s = range(1, 11)
# x_s = range(11, 1, -1) # Also works
d = dict([(i_s[index], x_s[index], ) for index in range(len(i_s))])
回答by Aditya Sihag
you can't hash a list like that. try this instead, it uses tuples
你不能散列这样的列表。试试这个,它使用元组
d[tuple([i for i in range(1,11)])] = True
回答by Bonifacio2
The main purpose of a list comprehension is to create a new list based on another one without changing or destroying the original list.
列表推导式的主要目的是在不改变或破坏原始列表的情况下根据另一个列表创建一个新列表。
Instead of writing
而不是写作
l = []
for n in range(1, 11):
l.append(n)
or
或者
l = [n for n in range(1, 11)]
you should write only
你应该只写
l = range(1, 11)
In the two top code blocks you're creating a new list, iterating through it and just returning each element. It's just an expensive way of creating a list copy.
在顶部的两个代码块中,您正在创建一个新列表,遍历它并只返回每个元素。这只是一种创建列表副本的昂贵方式。
To get a new dictionary with all keys set to the same value based on another dict, do this:
要根据另一个字典获取所有键设置为相同值的新字典,请执行以下操作:
old_dict = {'a': 1, 'c': 3, 'b': 2}
new_dict = { key:'your value here' for key in old_dict.keys()}
You're receiving a SyntaxError because when you write
你收到 SyntaxError 因为当你写
d = {}
d[i for i in range(1, 11)] = True
you're basically saying: "Set my key 'i for i in range(1, 11)' to True" and "i for i in range(1, 11)" is not a valid key, it's just a syntax error. If dicts supported lists as keys, you would do something like
您基本上是在说:“将我的键 'i for i in range(1, 11)' 设置为 True”和“i for i in range(1, 11)”不是有效键,它只是一个语法错误。如果 dicts 支持列表作为键,你会做类似的事情
d[[i for i in range(1, 11)]] = True
and not
并不是
d[i for i in range(1, 11)] = True
but lists are not hashable, so you can't use them as dict keys.
但列表不可散列,因此您不能将它们用作字典键。
回答by ehontz
I really like the @mgilson comment, since if you have a two iterables, one that corresponds to the keys and the other the values, you can also do the following.
我真的很喜欢@mgilson 评论,因为如果您有两个可迭代对象,一个对应于键,另一个对应于值,您还可以执行以下操作。
keys = ['a', 'b', 'c']
values = [1, 2, 3]
d = dict(zip(keys, values))
giving
给予
d = {'a': 1, 'b': 2, 'c': 3}
d = {'a':1,'b':2,'c':3}
回答by adonese
Consider this example of counting the occurrence of words in a list using dictionary comprehension
考虑这个使用字典理解计算列表中单词出现次数的例子
my_list = ['hello', 'hi', 'hello', 'today', 'morning', 'again', 'hello']
my_dict = {k:my_list.count(k) for k in my_list}
print(my_dict)
And the result is
结果是
{'again': 1, 'hi': 1, 'hello': 3, 'today': 1, 'morning': 1}

