How can I combine dictionaries with the same keys?

前端 未结 5 500
渐次进展
渐次进展 2020-12-01 17:35

I have a list of dictionaries like so:

dicts = [
    {\'key_a\': valuex1,
     \'key_b\': valuex2,
     \'key_c\': valuex3},

    {\'key_a\': valuey1,
     \         


        
5条回答
  •  孤街浪徒
    2020-12-01 17:46

    If all the dicts have the same set of keys, this will work:

    dict((k, [d[k] for d in dictList]) for k in dictList[0])
    

    If they may have different keys, you'll need to first built a set of keys by doing set unions on the keys of the various dicts:

    allKeys = reduce(operator.or_, (set(d.keys()) for d in dictList), set())
    

    Then you'll need to protect against missing keys in some dicts:

    dict((k, [d[k] for d in [a, b] if k in d]) for k in allKeys)
    

提交回复
热议问题