博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python字典添加字典_Python添加到字典
阅读量:2534 次
发布时间:2019-05-11

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

python字典添加字典

is one of the built-in data types. Dictionary elements are key-value pairs.

是内置数据类型之一。 字典元素是键值对。

Python添加到字典 (Python add to Dictionary)

There is no explicitly defined method to add a new key to the dictionary. If you want to add a new key to the dictionary, then you can use assignment operator with dictionary key.

没有明确定义的方法可以向字典添加新键。 如果要向字典添加新键,则可以将赋值运算符与字典键一起使用。

dict[key] = value

Note that if the key already exists, then the value will be overwritten.

请注意,如果键已经存在,则该值将被覆盖。

Let’s look at a simple example to add new keys to a dictionary.

让我们看一个简单的示例,将新键添加到字典中。

d = {'a': 1, 'b': 2}print(d)d['a'] = 100  # existing key, so overwrited['c'] = 3  # new key, so addd['d'] = 4print(d)

Output:

输出:

{'a': 1, 'b': 2}{'a': 100, 'b': 2, 'c': 3, 'd': 4}

What if we want to add a key only if it’s not present in the dictionary. We can use if condition to achieve this.

如果仅当字典中不存在键时我们想要添加键,该怎么办? 我们可以使用if条件来实现这一目标。

if 'c' not in d.keys():    d['c'] = 300if 'e' not in d.keys():    d['e'] = 5print(d)

Output:

输出:

{'a': 100, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

Notice that ‘c’ value is not changed because of if condition.

注意,由于if条件,'c'值不会更改。

That’s all for adding keys to a dictionary in python.

这就是为python中的字典添加键的全部。

翻译自:

python字典添加字典

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

你可能感兴趣的文章
微信支付之异步通知签名错误
查看>>
2016 - 1 -17 GCD学习总结
查看>>
linux安装php-redis扩展(转)
查看>>
Vue集成微信开发趟坑:公众号以及JSSDK相关
查看>>
技术分析淘宝的超卖宝贝
查看>>
i++和++1
查看>>
react.js
查看>>
P1313 计算系数
查看>>
NSString的长度比较方法(一)
查看>>
Azure云服务托管恶意软件
查看>>
My安卓知识6--关于把项目从androidstudio工程转成eclipse工程并导成jar包
查看>>
旧的起点(开园说明)
查看>>
生产订单“生产线别”带入生产入库单
查看>>
crontab导致磁盘空间满问题的解决
查看>>
java基础 第十一章(多态、抽象类、接口、包装类、String)
查看>>
Hadoop 服务器配置的副本数量 管不了客户端
查看>>
欧建新之死
查看>>
自定义滚动条
查看>>
APP开发手记01(app与web的困惑)
查看>>
笛卡尔遗传规划Cartesian Genetic Programming (CGP)简单理解(1)
查看>>