python dictionary related functions and method of operation

Dictionary Dictionary correlation function method ()

  • increase
dic = {"卢俊义":"玉麒麟"}
dic["小李广"] = "花荣"
dic["智多星"] = "吴用"
dic["入云龙"] = "公孙胜"
dic["霹雳火"] = "秦明"
print(dic)

fromkeys () uses a set of keys and default values ​​create a dictionary

list_var = ["a","b","c"]
dict_var = {}.fromkeys(list_var,None)
print(dict_var)

Precautions : abc three key points list is the same

list_var = ["a","b","c"]
dict_var = {}.fromkeys(list_var,[1,2,3])
print(dict_var)
dict_var["a"].append(4)
print(dict_var)
#运行结果
{'a': [1, 2, 3], 'b': [1, 2, 3], 'c': [1, 2, 3]}
{'a': [1, 2, 3, 4], 'b': [1, 2, 3, 4], 'c': [1, 2, 3, 4]}
#如果是可变数据类型三个字典对应的列表的数值的会改变
  • delete
dic ={'卢俊义': '玉麒麟', '小李广': '花荣', '智多星': '吴用', '入云龙': '公孙胜', '霹雳火': '秦明'}
# pop()       通过键去删除键值对 (若没有该键可设置默认值,预防报错)
res =dic.pop("霹雳火")
print(res)# 把删除的值作为返回
print(dic)

运行结果:
#秦明
#{'卢俊义': '玉麒麟', '小李广': '花荣', '智多星': '吴用', '入云龙': '公孙胜'}

设置默认值
dic ={'卢俊义': '玉麒麟', '小李广': '花荣', '智多星': '吴用', '入云龙': '公孙胜', '霹雳火': '秦明'}
res =dic.pop("asdasd","没有这个键")
print(res)

popitem () to delete the last key-value pairs

dic ={'卢俊义': '玉麒麟', '小李广': '花荣', '智多星': '吴用', '入云龙': '公孙胜', '霹雳火': '秦明'}
res = dic.popitem()
print(res)
#运行结果:
('霹雳火', '秦明')

clear () empty dictionary

dic ={'卢俊义': '玉麒麟', '小李广': '花荣', '智多星': '吴用', '入云龙': '公孙胜', '霹雳火': '秦明'}
res = dic.clear()
print(dic)
#删除后返回空字典
  • change

update () batch updates (there is the key to update, not the key is added)

#写法一:基于原有字典进行更新  (推荐)
dic_var = {"a":1,"b":2,"c":3}
dic_val = {"d":4,"e":5,"f":6}
dic_var.update(dic_val)
print(dic_var)

运行结果:
    {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6}
    
#写法二
dic_var.update(wb = "好人",zyh = "司机")
print(dictvar)
  • check
# get()    通过键获取值(若没有该键可设置默认值,预防报错)
dic_var = {"a":1,"b":2,"c":3}
res = dic_var.get("b")
print(res)

# 设置默认值 为了防止报错,程序异常终止;
dic_var = {"a":1,"b":2,"c":3}
res = dic_var.get("d","键不存在")
print(res)#键不存在

Other operating functions

1.keys()   将字典的键组成新的可迭代对象
dic ={'卢俊义': '玉麒麟', '小李广': '花荣', '智多星': '吴用', '入云龙': '公孙胜', '霹雳火': '秦明'}
res = dic.keys()
print(res) #dict_keys(['卢俊义', '小李广', '智多星', '入云龙', '霹雳火'])

#默认直接遍历字典,拿的是键
for i in dic:
    print(i)
    
2.values() 将字典中的值组成新的可迭代对象
res = dic.values()
print(res,type(res))
for i in res:
    print(i)
    
    
3.items()  将字典的键值对凑成一个个元组,组成新的可迭代对象 
res = dic.items()
print(res,type(res))

for i in res:
    print(i)

# 变量的解包
for k,v in res:
    print(k,v)

Guess you like

Origin www.cnblogs.com/CrownYP/p/11360544.html