Join multiple dicts to create new list with value as list of values of original dict

前端 未结 3 1312
小鲜肉
小鲜肉 2021-01-29 06:46

I\'m on Python 2.7 and have looked at several solutions here which works if you know how many dictionaries you are merging, but I could have anything between 2 to 5.

I

3条回答
  •  星月不相逢
    2021-01-29 07:08

    Use a defaultdict:

    In [18]: def gen_dictionaries():
        ...:     yield {'key1': 1, 'key2': 2, 'key3': 3}
        ...:     yield {'key1': 4, 'key2': 5, 'key3': 6}
        ...:
    
    In [19]: from collections import defaultdict
    
    In [20]: final = defaultdict(list)
    
    In [21]: for d in gen_dictionaries():
        ...:     for k, v in d.iteritems():
        ...:         final[k].append(v)
        ...:
    
    In [22]: final
    Out[22]: defaultdict(list, {'key1': [1, 4], 'key2': [2, 5], 'key3': [3, 6]})
    

提交回复
热议问题