create dict with multiple values out of two lists. group multiple keys into one

旧城冷巷雨未停 提交于 2021-02-05 10:53:07

问题


I have two list:

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

what I want is a dictionary like this:

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

I keep getting this:

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

I appreciate any advice!!


回答1:


You can try this:

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

or

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

Output:

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



回答2:


Upon reading a post suggestion from stackoverflow:

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

I have solved it.




回答3:


Easy way is to use zip.

dictionary = dict(zip(keys, values))



回答4:


You can try this:

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)

output:

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


来源:https://stackoverflow.com/questions/62550542/create-dict-with-multiple-values-out-of-two-lists-group-multiple-keys-into-one

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!