问题:Python字典理解

是否可以在Python(用于键)中创建字典理解?

在没有列表理解的情况下,您可以使用以下内容:

l = []
for n in range(1, 11):
    l.append(n)

我们可以将其简化为列表理解:l = [n for n in range(1, 11)]

但是,说我想将字典的键设置为相同的值。我可以:

d = {}
for n in range(1, 11):
     d[n] = True # same value for each

我已经试过了:

d = {}
d[i for i in range(1, 11)] = True

不过,我得到一个SyntaxErrorfor

另外(我不需要这部分,只是想知道),您能否将字典的键设置为一堆不同的值,例如:

d = {}
for n in range(1, 11):
    d[n] = n

字典理解有可能吗?

d = {}
d[i for i in range(1, 11)] = [x for x in range(1, 11)]

这也引发了SyntaxErrorfor

Is it possible to create a dictionary comprehension in Python (for the keys)?

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

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.

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.


回答 0

Python 2.7+中字典理解功能,但是它们不能完全按照您尝试的方式工作。就像列表理解一样,他们创建了一个字典。您不能使用它们将键添加到现有字典中。此外,您还必须指定键和值,尽管您当然可以根据需要指定一个哑数值。

>>> d = {n: n**2 for n in range(5)}
>>> print d
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

如果要将它们全部设置为True:

>>> d = {n: True for n in range(5)}
>>> print d
{0: True, 1: True, 2: True, 3: True, 4: True}

您似乎想要的是一种在现有字典上一次设置多个键的方法。没有直接的捷径。您可以像已经显示的那样循环,也可以使用字典理解来创建具有新值的新字典,然后oldDict.update(newDict)将新值合并到旧字典中。

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 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:

>>> 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.


回答 1

您可以使用dict.fromkeys类方法…

>>> dict.fromkeys(range(5), True)
{0: True, 1: True, 2: True, 3: True, 4: True}

这是创建所有键都映射到相同值的字典的最快方法。

但是千万不能用可变对象使用

d = dict.fromkeys(range(5), [])
# {0: [], 1: [], 2: [], 3: [], 4: []}
d[1].append(2)
# {0: [2], 1: [2], 2: [2], 3: [2], 4: [2]} !!!

如果您实际上不需要初始化所有键,那么a defaultdict也可能很有用:

from collections import defaultdict
d = defaultdict(True)

要回答第二部分,您需要的是dict理解:

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

您可能不应该这样做,但也可以创建一个子类,如果您重写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)
{}

You can use the dict.fromkeys class method …

>>> 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:

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 dict which works somewhat like a defaultdict if you override __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)
{}

回答 2

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

回答 3

我真的很喜欢@mgilson注释,因为如果您有两个可迭代项,一个与键相对应,另一个与值相对应,则还可以执行以下操作。

keys = ['a', 'b', 'c']
values = [1, 2, 3]
d = dict(zip(keys, values))

给予

d = {‘a’:1,’b’:2,’c’:3}

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.

keys = ['a', 'b', 'c']
values = [1, 2, 3]
d = dict(zip(keys, values))

giving

d = {‘a’: 1, ‘b’: 2, ‘c’: 3}


回答 4

在元组列表上使用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))])

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

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

回答 5

考虑以下示例,该示例使用字典理解来计算列表中单词的出现

my_list = ['hello', 'hi', 'hello', 'today', 'morning', 'again', 'hello']
my_dict = {k:my_list.count(k) for k in my_list}
print(my_dict)

结果是

{'again': 1, 'hi': 1, 'hello': 3, 'today': 1, 'morning': 1}

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}

回答 6

列表理解的主要目的是在不更改或破坏原始列表的基础上创建基于另一个列表的新列表。

而不是写作

    l = []
    for n in range(1, 11):
        l.append(n)

要么

    l = [n for n in range(1, 11)]

你应该只写

    l = range(1, 11)

在两个最重要的代码块中,您将创建一个新列表,对其进行迭代并仅返回每个元素。这只是创建列表副本的一种昂贵方法。

要获得一个新的字典,并且根据另一个字典将所有键设置为相同的值,请执行以下操作:

    old_dict = {'a': 1, 'c': 3, 'b': 2}
    new_dict = { key:'your value here' for key in old_dict.keys()}

您收到SyntaxError的原因是,在编写时

    d = {}
    d[i for i in range(1, 11)] = True

您基本上是在说:“将我的密钥’i for range(1,11)’中的i设置为True”和“ i for i in range(1,11)中的”)不是有效的密钥,这只是语法错误。如果将dicts支持的列表作为键,您将执行以下操作

    d[[i for i in range(1, 11)]] = True

并不是

    d[i for i in range(1, 11)] = True

但是列表不可散列,因此您不能将它们用作字典键。

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

    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

    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.


回答 7

您不能像这样散列表。试试这个,它使用元组

d[tuple([i for i in range(1,11)])] = True

you can’t hash a list like that. try this instead, it uses tuples

d[tuple([i for i in range(1,11)])] = True

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。