我有一个这样的dict列表,每个dict键的值是一个列表,
[{'mike':[500,1000,1500,2750,3000]},{'john':[750,1250,2000]},{'luke':[600,1100]}]
列表中的dict数将有所不同。
我怎样才能得到这样的输出,
按升序排列的每个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 - Python dict键按列表排序为值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37573373/