Home > Software engineering >  Compare two dict and change keys in second if keys exists as sub-value in first
Compare two dict and change keys in second if keys exists as sub-value in first

Time:03-02

Need help remapping the keys for d2 if they match the value for id in d1

d1={'A':{'id':'a'},'B':{'id':'b'}}
d2={'a':123,'b':123}

Expected output:

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

CodePudding user response:

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'])

Output:

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

CodePudding user response:

This is probably what you're after

d1={'A':{'id':'a'},'B':{'id':'b'}}
d2={'a':123,'b':123}

for key, id_map in d1.copy().items():  # view over soft copy won't mutate
    try:
        d1[key] = d2[id_map["id"]]
    except KeyError:
        pass
>>> d1
{'A': 123, 'B': 123}

However, unmapped values will remain the same (ie if there is C, but no id in its mapping, or no c in d2..)

>>> d1={'A':{'id':'a'},'B':{'id':'b'},'C':{'id':'c'}}
[..]
>>> d1
{'A': 123, 'B': 123, 'C': {'id': 'c'}}

If you want to discard unmapped values, you could do so here with del d1[key] in the except or simply create a new dict to pack the keys and values into (never added if KeyError is raised)
Alternatively, if this is an error (ie. C must exist), you can simply let KeyError raise to the caller and have it deal with the consequences

  • Related