使用两个列表中的多个值创建dict。将多个键分组为一个键

2024-06-02 05:59:54 发布

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

我有两份清单:

lists = ['a','b','c','d','e']
keys = [18,18,3,4,5]

我想要的是这样一本字典:

{18:['a','b'],3:'c',4:'d',5:'e'}

我一直在想:

{18: ['a', 'b', 'c', 'd', 'e'], 3: ['a', 'b', 'c', 'd', 'e'], 4: ['a', 'b', 'c', 'd', 'e'], 5: ['a', 'b', 'c', 'd', 'e']}

谢谢你的建议


Tags: 字典keys建议lists
3条回答

您可以尝试以下方法:

output = {}
for index, key in enumerate(keys):
    if not key in output:
        output[key] = lists[index]
    else:
        cur_val = output[key]
        if type(cur_val) == str:
            cur_val = [cur_val]
        
        cur_val.append(lists[index])        
        output[key] = cur_val
print(output)

输出:

{18: ['a', 'b'], 3: 'c', 4: 'd', 5: 'e'}

您可以尝试以下方法:

dicts = {key: [] for key in keys}
for k, v in zip(keys, lists):
    dicts[k].append(v)

from collections import defaultdict
dicts = defaultdict(list)
for k, v in zip(keys, lists):
    dicts[k].append(v)

输出:

{18: ['a', 'b'], 3: ['c'], 4: ['d'], 5: ['e']}

阅读stackoverflow的帖子建议后:

dictionary = {k: [values[i] for i in [j for j, x in enumerate(keys) if x == k]] for k in set(keys)}

我已经解决了

相关问题 更多 >