前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python中更新字典对象

python中更新字典对象

作者头像
qsjs
发布2020-06-09 09:01:51
1.4K0
发布2020-06-09 09:01:51
举报
文章被收录于专栏:MyPanda的学习笔记

最近用python做了一个小工具,涉及到如下的字典操作,特做笔记如下: 1. 用update方法更新字典: 用字典的update方法,这时候传递给update的必须是一个字典.

代码语言:javascript
复制
>>> d={}
>>> d.update({"key":123})
>>> d
{'key': 123}
>>> 
>>> n_d={"name":"testid"}
>>> d.update(n_d)
>>> d
{'name': 'testid', 'key': 123}
>>> 

2. 用赋值的方式进行更新: 上述update的方式进行字典更新,那么key必须是字符串,很多情况下,我们需要字典的key 和value都是变量(典型的把变量以及值存储到字典中),这时候用赋值的方式实现:

代码语言:javascript
复制
>>> d={}
>>> name="xiongmao"
>>> age=3
>>> d[name]=age
>>> d
{'xiongmao': 3}
>>> 

3. 多层字典的更新: 在实际的使用过程中,会遇到多重字典的情况(比如处理json格式的数据),这时候更新字典的时候,会看起来比较麻烦,下面是一个更新多重字典的函数例子:

代码语言:javascript
复制
#在这个例子当中,多重字典hostvardict 的更新遵循下面的原则: 
#A. 确认多重字典需要更新的部分,然后进行划分,同等level的部分看作一个变量,所以在下面的例子中,是两个变量.
#B. 每次调用字典对象update方法的时候,只更新其中一个变量,这样更清晰,所以在下面的例子中,一共调用了字典的两次update方法.
#C.  传入进来的字典用一个空字典,然后用try...except进行赋值处理;
#D. 更新完成,返回字典对象;
#hostname type should be string.
#hostvar type should be dict, the hostvar should not be empty. 
#hostvardict type is dict, just pass the empty dict  to this parameter . 
def hostvarformat(hostname,hostvar,hostvardict):
    try:
        hostvardict["_meta"]["hostvars"]  #It always trigger expect for 1st calling. 
    except:
        hostvardict={"_meta":{"hostvars":{}}}   #Create the dict first .
    hostvardict["_meta"]["hostvars"].update({hostname:{}})   #Update the dict with hostname.
    hostvardict["_meta"]["hostvars"][hostname].update(hostvar)     #Update the dict with sub dict hostvar. 
    return hostvardict   #Return the updated dict . 

遵照上述的原则,对于多重字典的更新应该也很容易理解了。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档