Python dict如何创建密钥或附加元素到密钥? [英] Python dict how to create key or append an element to key?
问题描述
我有一个空字典。名称: dict_x
它的值是列表的键。
从单独的迭代,我获得一个键(例如: key_123
)和一个项目(一个元组)放在 dict_x
的值 key_123
。
如果这个密钥已经存在,我想附加这个项目。
如果此键不存在,我想用空列表创建它,然后附加到它,或者用它创建一个元组。
将来再次出现这个关键字,因为它存在,我想要再次附加值。
我的代码包括:
获取密钥和值。
查看 键是否存在于
dict_x
。
如果没有创建它:
dict_x [key] == []
之后:
dict_x [key] .append(value)
这样做吗?我试图使用 try / except
块?
使用< a href =http://docs.python.org/library/stdtypes.html#dict.setdefault =noreferrer> dict.setdefault()
:
dic.setdefault(key,[])。append(value)
help(dict.setdefault):
setdefault(...)
D.setdefault(k [,d]) - > D.get(k,d),如果k不在D
中,也设置D [k] = d
I'm new to Python. Not only am I learning its functions, types and such, but also I am trying to learn the Pythonic ways to do things and hence my question:
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?
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
这篇关于Python dict如何创建密钥或附加元素到密钥?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!