Search code examples
pythondictionaryordereddictionarydefaultdict

Joining two Python Dictionaries on key


Have two Dictionaries in Python and would like to make a join using a key.

The first dictionary "d" is OrderedDict like this:

[OrderedDict([
          ('id', '1'),
          ('date', '20170101'),
OrderedDict([
          ('id', '2'),
          ('date', '20170102'),
OrderedDict([
          ('id', '3'),
          ('date', '20170102')]

The second one "dd" is defaultdict and it's like this:

defaultdict(int, {'1': 14, '2': 5, '3': 7})

I want to make a join using possibilities of "operator" library and using keys but the approach is not working for me because I dont know exactly how should I treat the keys in defaultdict:

sort_key = operator.itemgetter("id")

ks=[ k for k in dd.keys()]

for i, j in zip(sorted(d, key=sort_key), sorted(dd,key=ks)):
    i.update(j)

How should I correctly perform the joining?

Desirable output will be OrderedDict with additional values from the second dictionary:

[OrderedDict([
          ('id', '1'),
          ('date', '20170101'),
          ('quantity', '14'),
OrderedDict([
          ('id', '2'),
          ('date', '20170102'),
          ('quantity', '5'),
OrderedDict([
          ('id', '3'),
          ('date', '20170102'),
          ('quantity', '7')]

Thanks!


Solution

  • You can try this:

    from collections import OrderedDict, defaultdict
    d = [OrderedDict([
          ('id', '1'),
          ('date', '20170101')]),
        OrderedDict([
          ('id', '2'),
          ('date', '20170102')]),
        OrderedDict([
          ('id', '3'),
          ('date', '20170102')])]
    
    marker = defaultdict(int, {'1': 14, '2': 5, '3': 7})
    new_d = [OrderedDict([(a, b) for a, b in i.items()]+[('quantity', marker[i['id']])]) for i in d] 
    

    Output:

    [OrderedDict([('id', '1'), ('date', '20170101'), ('quantity', 14)]),
    OrderedDict([('id', '2'), ('date', '20170102'), ('quantity', 5)]),
    OrderedDict([('id', '3'), ('date', '20170102'), ('quantity', 7)])]