Python dict 如何创建键或将元素附加到键?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12905999/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:08:16  来源:igfitidea点击:

Python dict how to create key or append an element to key?

pythonpython-2.7python-3.xdictionary

提问by Phil

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

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

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.

从单独的迭代中,我获得了一个键(例如:)key_123和一个项目(一个元组)以放置在dict_x的值列表中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 NOTkey exists in dict_x.

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

Afterwards: dict_x[key].append(value)

获取键值。

查看中是否存在NOTdict_x

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

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

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

这是这样做的方法吗?我应该尝试使用try/except块吗?

采纳答案by Ashwini Chaudhary

Use dict.setdefault():

使用dict.setdefault()

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

help(dict.setdefault):

帮助(dict.setdefault)

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

回答by iMom0

You can use defaultdictin collections.

您可以使用defaultdictcollections

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)

回答by Nathan Villaescusa

You can use a defaultdictfor this.

您可以为此使用defaultdict

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

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

这比setdefault因为您最终不会创建您最终不会使用的新列表而略有效率。每次调用setdefault都会创建一个新列表,即使该项目已存在于字典中。

回答by antak

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:

以下是执行此操作的各种方法,因此您可以比较它的外观并选择您喜欢的。我以我认为最“pythonic”的方式订购它们,并评论了乍一看可能不明显的优点和缺点:

Using collections.defaultdict:

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

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

Using dict().setdefault():

使用dict().setdefault()

dict_x = {}

...

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

Cons: Inefficient creation of unused list()s.

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

Using try ... except:

使用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]