Search code examples
python-3.xordereddictionary

How to add two OrderedDict when key is same in both the OrderedDicts?


My first orderedDic is

OrderedDict([('3LEmxb4G9q5XnP9H5653ncMAbAgbDCzz8U', {'value': 0.5, 'valueSat': 50000000, 'txid': '4c4e1609392f6744cdf9ff57614eb5f6905f39baba8f046c3b3bd5a1e6b573c8'}), ('1ErSPkXKfdVgjseia1psccr6ng4zbyLNSE', {'value': 0.01349045, 'valueSat': 1349045, 'txid': '4c4e1609392f6744cdf9ff57614eb5f6905f39baba8f046c3b3bd5a1e6b573c8'})])

My second orderedDict is

OrderedDict([('3LEmxb4G9q5XnP9H5653ncMAbAgbDCzz8U', {'account_id': None, 'last_block': '', 'n_conf': 0, 'total_confirmations': 3}), ('1ErSPkXKfdVgjseia1psccr6ng4zbyLNSE', {'account_id': None, 'last_block': '', 'n_conf': 0, 'total_confirmations': 6})])

In the above two orderedDict, keys are same but values are different. How to merge the values of the same keys from both the orderedDicts and make one new?


Solution

  • Here is the code to it:

    from collections import OrderedDict
    a= OrderedDict([('3LEmxb4G9q5XnP9H5653ncMAbAgbDCzz8U', {'value': 0.5, 'valueSat': 50000000, 'txid': '4c4e1609392f6744cdf9ff57614eb5f6905f39baba8f046c3b3bd5a1e6b573c8'}), ('1ErSPkXKfdVgjseia1psccr6ng4zbyLNSE', {'value': 0.01349045, 'valueSat': 1349045, 'txid': '4c4e1609392f6744cdf9ff57614eb5f6905f39baba8f046c3b3bd5a1e6b573c8'})])
    b=OrderedDict([('3LEmxb4G9q5XnP9H5653ncMAbAgbDCzz8U', {'account_id': None, 'last_block': '', 'n_conf': 0, 'total_confirmations': 3}), ('1ErSPkXKfdVgjseia1psccr6ng4zbyLNSE', {'account_id': None, 'last_block': '', 'n_conf': 0, 'total_confirmations': 6})])
    c=OrderedDict()
    
    for key in a:
        temp=b[key]
        temp.update(a[key])
        c[key]=temp
    print c
    

    Your new dictionary is stored in c. Remember .update() updates the dictionary itself and returns None.