Python dict如何创建密钥或附加元素到密钥? [英] Python dict how to create key or append an element to key?

查看:98
本文介绍了Python dict如何创建密钥或附加元素到密钥?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很习惯Python。不仅我学习它的功能,类型等,而且我正在尝试学习Pythonic的方式来做事情,因此我的问题是:



我有一个空字典。名称: 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆