1.用拉链函数zip()将字典转换成元组对!函数中的两个参数必须是序列!
p = {'name':'zhangsanfeng','age':18,'gender':'nan'}
print(list(zip(p.keys(),p.values())))
>>>[('name', 'zhangsanfeng'), ('age', 18), ('gender', 'nan')]
p = {'name':'zhangsanfeng','age':18,'gender':'nan'}
print(zip(p.keys(),p.values()))
a = zip(p.keys(),p.values())
for i in a :
print(i)
>>><zip object at 0x00000241C1C87C88>
('name', 'zhangsanfeng')
('age', 18)
('gender', 'nan')
可以借助zip函数和max函数,取出一一对应的的keys比较或者values比较
一般序列里面的值可以被迭代,就可以使用max函数,不同类型的元素不能比较大小
dic_ky = {"k1":"001","k2":"002","k3":"003"}
print(max(zip(dic_ky.values(),dic_ky.keys())))
>>>('003','k3')
a = [
{'name':'zhangsan','age':12},
{'name':'lisi','age':14},
{'name':'wanger','age':10},
{'name':'mazi','age':15}
]
print(max(a,key=lambda dic:dic['age']))
>>>{'name': 'mazi', 'age': 15}
2.字典的setdefault方法
dic_ky = {"k1":"001","k2":"002"}
v1 = dic_ky.setdefault('k3','003') #k3不存在,插入字典后返回一个值
v2 = dic_ky.setdefault('k1','111') #设置失败,返回看字典K1的原值001
print(v1) #输出:003
print(v2) #输出:001
print(dic_ky)#{'k1': '001', 'k2': '002', 'k3': '003'}