繁体   English   中英

Python dict键按列表排序为值

[英]Python dict key Sorted by list as value

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

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

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

我如何得到这样的输出,每个字典值按升序排列

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

使用列表 str.joinstr.join列表展平为元组列表(value, key) ,使用sorted对值进行排序,使用str.join格式化输出。

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

# flat the list of dicts as a list of tuples (value, key), sort them
result = sorted([(item, k) for d in list_dicts for k, l in d.items() for item in l])

# format output
print('\n'.join([':'.join([str(i) for i in t]) for t in result]))
# Output
500:mike
600:luke
750:john
1000:mike
1100:luke
1250:john
1500:mike
2000:john
2750:mike
3000:mike

您使用itertools来解决此问题:

from itertools import product, chain

LL = list(chain(*[list(product(i.keys(), i.values()[0])) for i in L]))
sorted(LL, key=lambda x: x[1])

Out[152]:
[('mike', 500),
 ('luke', 600),
 ('john', 750),
 ('mike', 1000),
 ('luke', 1100),
 ('john', 1250),
 ('mike', 1500),
 ('john', 2000),
 ('mike', 2750),
 ('mike', 3000)]
a,b=[],[]
for i in g:
    for k in i.values()[0]:
        a.append(k)
        b.append(i.keys())

print sorted(zip(a,b))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM