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

后端 未结 4 1541
旧时难觅i
旧时难觅i 2021-01-28 23:44

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\',\'         


        
4条回答
  •  不要未来只要你来
    2021-01-28 23:48

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

提交回复
热议问题