Comparing/combining two dictionaries

后端 未结 1 884
醉话见心
醉话见心 2021-01-23 03:04

I have two dictionaries with key-value pairs as follows:

dict-1  ch:23, 100
        ch:24, 95

dict-2  Ch:23, 98
        ch:25, 100

Not all key

1条回答
  •  孤街浪徒
    2021-01-23 03:27

    Note If you are using a dictionary (Unless OrderedDict), the order would not be preserved, so the final order of your result would not be same as you depicted in your example

    Coming back to your example If

    >>> d1={'ch:23': 100, 'ch:24': 95}
    >>> d2={'ch:23': 98 ,'ch:25': 100}
    

    You can try this

    >>> d3=collections.defaultdict(list)
    >>> for k,e in d1.items()+d2.items():
        d3[k].append(e)
    

    If you want to preserve the Order, you need to create the original dictionary as an ordered dict in the first instance

    Then you can do as

    >>> d1
    OrderedDict([('ch:23', 100), ('ch:24', 95)])
    >>> d2
    OrderedDict([('ch:23', 98), ('ch:25', 100)])
    >>> d3=collections.OrderedDict()
    >>> for k,e in d1.items()+d2.items():
        d3.setdefault(k,[]).append(e)   
    >>> d3
    OrderedDict([('ch:23', [100, 98]), ('ch:24', [95]), ('ch:25', [100])])
    >>> 
    

    0 讨论(0)
提交回复
热议问题