博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python将新项添加到字典[重复]
阅读量:2289 次
发布时间:2019-05-09

本文共 1692 字,大约阅读时间需要 5 分钟。

本文翻译自:

This question already has an answer here: 这个问题在这里已有答案:

  • 14 answers 14个答案

I want to add an item to an existing dictionary in python. 我想在python中将项添加到现有字典中。 For example, this is my dictionary: 例如,这是我的字典:

default_data = {            'item1': 1,            'item2': 2,}

I want to add new item such that: 我想添加新项目,以便:

default_data = default_data + {'item3':3}

How to achieve this? 怎么做到这一点?


#1楼

参考:


#2楼

default_data['item3'] = 3

Easy as py. 很容易py。

Another possible solution: 另一种可能的方案

default_data.update({'item3': 3})

which is nice if you want to insert multiple items at once. 如果你想一次插入多个项目,那就太好了。


#3楼

It can be as simple as: 它可以很简单:

default_data['item3'] = 3

As says, you can use to add more than one item. 正如所说,您可以使用来添加多个项目。 An example: 一个例子:

default_data.update({'item4': 4, 'item5': 5})

Please see the docs about and . 请将有关的文档和 。


#4楼

It occurred to me that you may have actually be asking how to implement the + operator for dictionaries, the following seems to work: 我突然想到你可能实际上已经在询问如何为字典实现+运算符,以下似乎有效:

>>> class Dict(dict):...     def __add__(self, other):...         copy = self.copy()...         copy.update(other)...         return copy...     def __radd__(self, other):...         copy = other.copy()...         copy.update(self)...         return copy... >>> default_data = Dict({'item1': 1, 'item2': 2})>>> default_data + {'item3': 3}{'item2': 2, 'item3': 3, 'item1': 1}>>> {'test1': 1} + Dict(test2=2){'test1': 1, 'test2': 2}

Note that this is more overhead then using dict[key] = value or dict.update() , so I would recommend against using this solution unless you intend to create a new dictionary anyway. 请注意,这比使用dict[key] = valuedict.update()更有开销,所以我建议不要使用此解决方案,除非您打算创建一个新的字典。

转载地址:http://lscnb.baihongyu.com/

你可能感兴趣的文章
MySQL数据类型
查看>>
MySQL SQL语句最常见的分类
查看>>
MySQL用户权限
查看>>
MySQL数据备份
查看>>
MySQL使用explain检查索引执行计划
查看>>
MySQL字符集
查看>>
MySQL存储引擎
查看>>
MySQL主从同步
查看>>
MySQL半同步复制
查看>>
MySQL主库宕机从库提权
查看>>
MySQL主主模式
查看>>
MySQL错误代码
查看>>
MySQL binlog的三种模式
查看>>
MySQL利用binlog增量恢复数据库
查看>>
Tomcat多实例多应用
查看>>
Tomcat启动慢解决方法
查看>>
Tomca主配置文件详解
查看>>
Tomcat创建虚拟主机
查看>>
Tomcat集群
查看>>
Tomcat DeltaManager集群共享session
查看>>