gpt4 book ai didi

Python dict 键按列表排序为值

转载 作者:太空宇宙 更新时间:2023-11-03 15:01:24 26 4
gpt4 key购买 nike

我有一个这样的字典列表,每个字典键的值是一个列表,

[{'mike':[500,1000,1500,2750,3000]},{'john':[750,1250,2000]},{'luke':[600,1100]}]

列表中字典的数量会有所不同。

我怎样才能得到这样的输出,每个dict值按升序排列

500:mike
600:luke
750:john
1000:mike
1100:luke
1250:john
1500:mike
2000:john
2750:mike
3000:mike

最佳答案

一个类轮:

result = sorted(((item, key) for d in x for (key, value) in d.items() for item in value), key=lambda x: x[0])

for elem in result:
print ({elem[0]}:{elem[0]}.format(elem=elem)

多线:

x = [{"mike":[500,1000,1500,2750,3000]},{"john":[750,1250,2000]},{"luke":[600,1100]}]
result = []
for item in x:
for key, value in item.iteritems():
for v in value:
result.append((v, key))
result.sort(key=lambda x: x[0])
for elem in result:
print ({elem[0]}:{elem[0]}.format(elem=elem)

# outputs
500:mike
600:luke
750:john
1000:mike
1100:luke
1250:john
1500:mike
2000:john
2750:mike
3000:mike

关于Python dict 键按列表排序为值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37573373/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com