Search code examples
pythondictionarynestedmatching

Compare two dict and change keys in second if keys exists as sub-value in first


Need help remapping the keys for d2 if they match the value for id in d1. In case there are keys that are unmatched, drop them.

d1={'A':{'id':'a'},'B':{'id':'b'}}
d2={'a':1,'b':2, 'c':3}

Expected output:

{'A': 1, 'B': 2}

Solution

  • You could traverse d1 and use d2 as a lookup to modify values:

    for k, d in d1.items():
        d1[k] = d2.get(d['id'])
    

    If you want to modify df2 instead, you could use a dict comprehension:

    d2 = {k: d2.get(d['id']) for k, d in d1.items()}
    

    or use two loops (once to modify values of keys that exist in df1 and once to remove any keys that don't exist in df1):

    for k, d in d1.items():
        d2[k] = d2.pop(d['id'])
    for k in list(d2.keys() - d1.keys()):
        d2.pop(k)
    

    Output:

    {'A': 123, 'B': 123}