Python字典
#!/usr/bin/env python
#coding:utf-8
info = {
‘name1‘: "jenkins",
‘name2‘: "docker",
‘name3‘: "elk",
‘name4‘: "zabbix"
}
#增加
info["name5"] = "redis"
print info
#刪除
del info["name4"]
print info
info.pop("name2") #標準刪除資勢
print info
info.popitem() #隨機刪除
print info
#修改
info["name3"] = "python"
print info
#查詢
print info
print info["name1"] #如果一個key不存在,就報錯,get不會,不存在只返回None
print info.get("name1") #獲取
print "name1" in info #標準用法,
print info.has_key("name1") #python2用法,python3裏沒有
#多級字典嵌套及操作
zhongguo = {
"gz": {
"tianhe": ["this is tianhe","youkongguolaiwan"],
"yunxiu": ["this is yuexiu","youkongguolaiwan"],
},
"foshan": {
"chancheng": ["this is chanchen","youkongguolaiwan"],
"gaoli": ["this is gaoli","youkongguolaiwan"],
}
}
print zhongguo
zhongguo["foshan"]["gaoli"][1] = "this is test"
print zhongguo
print zhongguo["foshan"]["gaoli"][1] == "this is test"
zhongguo.setdefault("jiangmen",{"www.baidu.com":[1,2]})#添加一個新的字典
print zhongguo
info2 = {
‘test1‘: "xiao ming",
‘test2‘: "xiao qiang",
‘test3‘: "xiao lso"
}
b = {
‘test1‘: "woqr",
1: 3,
2: 4
}
print info2
info2.update(b) #更新並合並info
print info2
#把一個字典轉成了一個列表
print info2.items()
print info
print dict.fromkeys([6,7,8],"test") #初始化一個字典
c = dict.fromkeys([6,7,8],[111,{"name":‘jesfw‘},222])
print c
c[7][1][‘name‘] = "Jack"
print c
for i in info:
print i,info[i] #打印key,value
for k,v in info.items():
print k,v
#上面這個比下面高效,通過循環通過key索引找出值
本文出自 “YHT的運維筆記” 博客,請務必保留此出處http://yht1990.blog.51cto.com/9014030/1942747
Python字典