Python dict的五种创建方式和四种合并自定义排序方式
创建方式
# 1.
a = dict(one=1,two=2,three=3)
# 2.
a = dict({'one':1,'two':2,'three':3})
# 3.zip
a = dict(zip(['one','two','three'],[1,2,3]))
#4.列表元组
a = dict([('one',1),('two',2),('three',3)])
# 5.字典推导
a = {k:v for k,v in zip(['one','two','three'],[1,2,3])}
合并方式
d1 = {'usr': 'root', 'pwd': '123456'}
d2 = {'ip': '127.0.0.1', 'port': '8080'}
# 1.dict.update
d3={}
d3.update(d1)
d3.update(d2)
# 2.python3.5后
d3 = {**d1,**d2}
# 3.dict(d1,**d2)
d3 = dict(d1,**d2)
# 4.字典的常规处理
for k, v in d1.items():
d3[k] = v
for k, v in d2.items():
d3[k] = v
print('四:', d3)
排序
dict_data = {6: 9, 10: 5, 3: 11, 8: 2, 7: 6}
# 1.按key由小到大排序
d = sorted(dict_data,key=lambda x:x[0])
# 2.按value排序,reverse:逆序
d = sorted(dict_data,key=lambda x:x[1],reverse=True)
# 3.itemgetter
from operator import itmegetter
d = sorted(dict_data,key=itemgetter('score'))
# 4.cmp_to_key 自定义排序
from functools import cmp_to_key
rank = [
{'score': 12, 'time': '2022-08-04'},
{'score': 23, 'time': '2022-08-01'},
{'score': 23, 'time': '2022-07-24'},
{'score': 10, 'time': '2022-07-16'},
]
def custom_sorted(x,y)
# 先比较score,score相同在比较时间
if x["score"] >y["score"]:
return 1
is x["score"] <y["score"]:
return -1
# 时间由小到大
if x["score"] == y["score"]:
if x["time"] > y["time"]:
return 1
else:
return -1
to_rank = sorted(rank,key=cmp_to_key(cusom_sorted))
# 5.x.get("")
to_rank = sorted(rank,key=lambda x:x.get("score")
最大值
prices = {
'ACME': 45.23,
'AAPL': 612.78,
'IBM': 205.55,
'HPQ': 37.20,
'FB': 10.75,
}
# 1.根据value获取最大值:输出最大值的key
max_ = max(prices,key=lambda k:prices[k])
pritn(max_)
>>AAPL
# 2.获取最大值key,value
print(max(zip(prices.values(),prices.keys())))
>>(612.78, 'AAPL')