Python字典理解

本文翻译自:Python Dictionary Comprehension

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 SyntaxError on the for . 不过,我得到一个SyntaxErrorfor

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 SyntaxError on the for . 这也会在for上引发SyntaxError


#1楼

参考:https://stackoom.com/question/ys5P/Python字典理解


#2楼

You can use the dict.fromkeys class 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 not use 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 need to initialize all the keys, a defaultdict might be useful as well: 如果您实际上不需要初始化所有键,那么defaultdict也可能有用:

from collections import defaultdict
d = defaultdict(True)

To answer the second part, a dict-comprehension is just what you need: 要回答第二部分,您需要的是dict理解:

{k: k for k in range(10)}

You probably shouldn't do this but you could also create a subclass of dict which works somewhat like a defaultdict if you override __missing__ : 您可能不应该这样做,但是您还可以创建dict的子类,如果您覆盖__missing__则该子类的工作方式类似于defaultdict

>>> 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)
{}

#3楼

There are dictionary comprehensions in Python 2.7+ , but they don't work quite the way you're trying. Python 2.7+中字典理解功能 ,但是它们不能完全按照您尝试的方式工作。 Like a list comprehension, they create a new dictionary; 就像列表理解一样,他们创建了一个字典。 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. 同样,您必须指定键和值,尽管您当然可以根据需要指定一个虚拟值。

>>> 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)将新值合并到旧字典中。


#4楼

>>> {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}

#5楼

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))])

#6楼

you can't hash a list like that. 您不能像这样散列表。 try this instead, it uses tuples 试试这个代替,它使用元组

d[tuple([i for i in range(1,11)])] = True
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值