如何使用列表理解来制作一个以列表为值的dict

2024-04-25 14:21:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个如下的列表,我想使用列表理解将其转换为如下所示的输出。感谢您的帮助

a = [{'type': 'abc', 'values': 1},
     {'type': 'abc', 'values': 2},
     {'type': 'abc', 'values': 3},
     {'type': 'xyz', 'values': 4},
     {'type': 'xyz', 'values': 5},
     {'type': 'pqr', 'values': 6},
     {'type': 'pqr', 'values': 8},
     {'type': 'abc', 'values': 9},
     {'type': 'mno', 'values': 10},
     {'type': 'def', 'values': 11}]

这是我期望的结果

output = {'abc': [1,2,3,9], 'xyz': [4,5], 'pqr': [6,8], 'mno': [10], 'def': [11]}

Tags: 列表outputdeftypevaluesabcxyzmno
2条回答
from operator import itemgetter
from itertools import groupby

a = [{'type': 'abc', 'values': 1},
     {'type': 'abc', 'values': 2},
     {'type': 'abc', 'values': 3},
     {'type': 'xyz', 'values': 4},
     {'type': 'xyz', 'values': 5},
     {'type': 'pqr', 'values': 6},
     {'type': 'pqr', 'values': 8},
     {'type': 'abc', 'values': 9},
     {'type': 'mno', 'values': 10},
     {'type': 'def', 'values': 11}]

typegetter = itemgetter('type')
valuesgetter = itemgetter('values')

groups = groupby(sorted(a, key=typegetter), key=typegetter)

print {k:list(map(valuesgetter, v)) for k, v in groups}
a = [{'type': 'abc', 'values': 1},
     {'type': 'abc', 'values': 2},
     {'type': 'abc', 'values': 3},
     {'type': 'xyz', 'values': 4},
     {'type': 'xyz', 'values': 5},
     {'type': 'pqr', 'values': 6},
     {'type': 'pqr', 'values': 8},
     {'type': 'abc', 'values': 9},
     {'type': 'mno', 'values': 10},
     {'type': 'def', 'values': 11}]

output = {}
for item in a:
    output[item['type']] = [item['values']] if output.get(item['type'], None) is None else output[item['type']] + [item['values']]
print output

相关问题 更多 >