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

Python 使用两个列表中的多个值创建dict。将多个键分组为一个键,python,dictionary,Python,Dictionary,我有两份清单: 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']} 谢谢你的建议 阅读stac

我有两份清单:

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']}

谢谢你的建议

阅读stackoverflow的帖子建议后:

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

我已经解决了。

简单的方法是使用zip

dictionary = dict(zip(keys, values))
您可以尝试以下方法:

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)
dicts = {key: [] for key in keys}
for k, v in zip(keys, lists):
    dicts[k].append(v)
输出:

{18: ['a', 'b'], 3: 'c', 4: 'd', 5: 'e'}
您可以尝试以下方法:

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)
dicts = {key: [] for key in keys}
for k, v in zip(keys, lists):
    dicts[k].append(v)

输出:

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

这将生成{18:'b',3:'c',4:'d',5:'e'}此输出而不是{18:['a','b'],3:'c',4:'d',5:'e'}那么如何:对于键,ziplist_one中的值,list_two中的值:d[key]。append方法将失败,因为该键在列表中没有值。您可以使用defaultdictlist来解决这个问题,但是即使只有一个元素,您也会得到列表,但是OP只是希望在这种情况下直接使用该元素。您可以通过再次浏览字典并用条目替换一个元素列表来解决这个问题。感谢您发布答案!请注意,现实情况下,在问题海报已经发布了他们自己满意的答案后,这不太可能被接受。似乎即使一个键只有一个元素,也会生成列表,但您要求这些元素直接显示为值。