To merge two dictionaries of list in Python

前端 未结 6 1497

There are two dictionaries

x={1:[\'a\',\'b\',\'c\']}
y={1:[\'d\',\'e\',\'f\'],2:[\'g\']}

I want another dictionary z which is a merged one

6条回答
  •  北荒
    北荒 (楼主)
    2020-12-19 14:15

    Counter() can be used in this case:

    >>> x={1:['a','b','c']}
    >>> y={1:['d','e','f'],2:['g']}
    >>> from collections import Counter
    >>> Counter(x) + Counter(y)
    Counter({2: ['g'], 1: ['a', 'b', 'c', 'd', 'e', 'f']})
    

    If desired result is a dict. You can use the following:

    z = dict(Counter(x) + Counter(y))
    

提交回复
热议问题