Python dict如何创建密钥或向密钥添加元素?

问题:Python dict如何创建密钥或向密钥添加元素?

我有一本空字典。名称:dict_x 将具有其值为列表的键。

从一个单独的迭代中,我获得一个键(例如:)key_123和一个项目(一个元组),将其放置在dict_xvalue 的列表中key_123

如果该键已经存在,我想添加此项。如果此键不存在,我想用一个空列表创建它,然后追加到它或只在其中添加一个元组。

将来再次出现此键时,由于它存在,我希望再次添加该值。

我的代码包含以下内容:

获取关键和价值。

看看中是否存在NOTdict_x

如果没有创建它: dict_x[key] == []

之后: dict_x[key].append(value)

这是这样做的方式吗?我应该尝试使用try/except积木吗?

I have an empty dictionary. Name: dict_x It is to have keys of which values are lists.

From a separate iteration, I obtain a key (ex: key_123), and an item (a tuple) to place in the list of dict_x‘s value key_123.

If this key already exists, I want to append this item. If this key does not exist, I want to create it with an empty list and then append to it or just create it with a tuple in it.

In future when again this key comes up, since it exists, I want the value to be appended again.

My code consists of this:

Get key and value.

See if NOT key exists in dict_x.

and if not create it: dict_x[key] == []

Afterwards: dict_x[key].append(value)

Is this the way to do it? Shall I try to use try/except blocks?


回答 0

用途dict.setdefault()

dic.setdefault(key,[]).append(value)

help(dict.setdefault)

    setdefault(...)
        D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D

Use dict.setdefault():

dic.setdefault(key,[]).append(value)

help(dict.setdefault):

    setdefault(...)
        D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D

回答 1

这是执行此操作的各种方法,因此您可以比较它的外观并选择所需的内容。我以我认为最“ pythonic”的方式对它们进行了排序,并评论了乍一看可能并不明显的利弊:

使用collections.defaultdict

import collections
dict_x = collections.defaultdict(list)

...

dict_x[key].append(value)

优点:可能是最佳性能。缺点:在Python 2.4.x中不可用。

使用dict().setdefault()

dict_x = {}

...

dict_x.setdefault(key, []).append(value)

缺点:未使用list()s的创建效率低。

使用try ... except

dict_x = {}

...

try:
    values = dict_x[key]
except KeyError:
    values = dict_x[key] = []
values.append(value)

要么:

try:
    dict_x[key].append(value)
except KeyError:
    dict_x[key] = [value]

Here are the various ways to do this so you can compare how it looks and choose what you like. I’ve ordered them in a way that I think is most “pythonic”, and commented the pros and cons that might not be obvious at first glance:

Using collections.defaultdict:

import collections
dict_x = collections.defaultdict(list)

...

dict_x[key].append(value)

Pros: Probably best performance. Cons: Not available in Python 2.4.x.

Using dict().setdefault():

dict_x = {}

...

dict_x.setdefault(key, []).append(value)

Cons: Inefficient creation of unused list()s.

Using try ... except:

dict_x = {}

...

try:
    values = dict_x[key]
except KeyError:
    values = dict_x[key] = []
values.append(value)

Or:

try:
    dict_x[key].append(value)
except KeyError:
    dict_x[key] = [value]

回答 2

您可以为此使用defaultdict

from collections import defaultdict
d = defaultdict(list)
d['key'].append('mykey')

这比setdefault没有创建最终不会使用的新列表要有效得多。每次调用setdefault都会创建一个新列表,即使该条目已存在于字典中也是如此。

You can use a defaultdict for this.

from collections import defaultdict
d = defaultdict(list)
d['key'].append('mykey')

This is slightly more efficient than setdefault since you don’t end up creating new lists that you don’t end up using. Every call to setdefault is going to create a new list, even if the item already exists in the dictionary.


回答 3

您可以使用defaultdictcollections

来自doc的示例:

s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
d = defaultdict(list)
for k, v in s:
    d[k].append(v)

You can use defaultdict in collections.

An example from doc:

s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
d = defaultdict(list)
for k, v in s:
    d[k].append(v)

回答 4

dictionary['key'] = dictionary.get('key', []) + list_to_append
dictionary['key'] = dictionary.get('key', []) + list_to_append