Python dict 如何创建键或将元素附加到键? [英] Python dict how to create key or append an element to key?
问题描述
我有一本空字典.名称:dict_x
它是具有值是列表的键.
I have an empty dictionary. Name: dict_x
It is to have keys of which values are lists.
从单独的迭代中,我获得了一个键(例如:key_123
)和一个项目(一个元组)以放置在 dict_x
的值列表中<代码>key_123.
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.
我的代码包括:
获取键和值.
查看 dict_x
中是否存在 NOT 键.
See if NOT key exists in dict_x
.
如果没有创建它:dict_x[key] == []
之后:dict_x[key].append(value)
这是这样做的方式吗?我应该尝试使用 try/except
块吗?
Is this the way to do it? Shall I try to use try/except
blocks?
推荐答案
dict.setdefault(key,[]).append(value)
帮助(dict.setdefault):
setdefault(...)
D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
这篇关于Python dict 如何创建键或将元素附加到键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!