Python dict键按列表排序为值

时间:2016-06-01 15:48:47

标签: python list

我有一个这样的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

4 个答案:

答案 0 :(得分:2)

一个班轮:

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

答案 1 :(得分:1)

使用list comprehensions将字典列表展平为元组列表(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

答案 2 :(得分:1)

您使用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)]

答案 3 :(得分:0)

a,b=[],[]
for i in g:
    for k in i.values()[0]:
        a.append(k)
        b.append(i.keys())

print sorted(zip(a,b))