最近用python做了一个小工具,涉及到如下的字典操作,特做笔记如下:
1. 用update方法更新字典:
用字典的update方法,这时候传递给update的必须是一个字典.
>>> 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都是变量(典型的把变量以及值存储到字典中),这时候用赋值的方式实现:
>>> d={}
>>> name="xiongmao"
>>> age=3
>>> d[name]=age
>>> d
{'xiongmao': 3}
>>>
3. 多层字典的更新:
在实际的使用过程中,会遇到多重字典的情况(比如处理json格式的数据),这时候更新字典的时候,会看起来比较麻烦,下面是一个更新多重字典的函数例子:
#在这个例子当中,多重字典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 .
遵照上述的原则,对于多重字典的更新应该也很容易理解了。
网友评论