Home > Net >  Comparing keys and values in python dictionaries
Comparing keys and values in python dictionaries

Time:10-19

say I have two dictionaries d1 and d2 looking like this:

d1={569328: inf,
 574660: inf,
 1187498: 1,
 1226468: 2,
 1236571: inf,
 1239098: 1,
 1239277: 5,
 1239483: inf,
 1239622: 9,
 1239624: inf,
 1239749: inf,
 1334477: 6,
 1340405: inf,
 1340418: inf,
 1340462: 2,
 1340471: inf}
d2={596005: [569328],
 4321416: [1334477, 1187498],
 5802640: [569328, 1226468],
 6031690: [569328,
  1340462,
  1239622,
  1187498,
  1239277]}

What I would like to do is to substitute the items of d2 with the numbers in d1 whenever the item of d2 coincides with the key of d1. In other words I would like to obtain the following at the end:

d3={596005: [inf],
 4321416: [6, 1],
 5802640: [inf, 2],
 6031690: [inf,
  2,
  9,
  1,
  5]}

Please, be aware that my original dictionaries are much longer, hence solutions being not complex are preferred (I mean linear complexity would be great :))

Thanks a lot.

CodePudding user response:

You'll probably want to use the get method and some isinstance checks to protect against missing keys in those d2 lists and protect against getting something other than a list.

This will skip anything that's not a list. And it will use math.nan for cases when the numbers in the d2 lists don't match up any of the keys in d1, which I'm guessing can easily happen.

import math

d1={569328: math.inf,
    574660: math.inf,
    1187498: 1,
    1226468: 2,
    1236571: math.inf,
    1239098: 1,
    1239277: 5,
    1239483: math.inf,
    1239622: 9,
    1239624: math.inf,
    1239749: math.inf,
    1334477: 6,
    1340405: math.inf,
    1340418: math.inf,
    1340462: 2,
    1340471: math.inf}

d2={596005: [569328],
    4321416: [1334477, 1187498],
    5802640: [569328, 1226468],
    6031690: [569328, 1340462, 1239622, 1187498, 1239277]}

missing_default = math.nan
for key, val_list in d2.items():
    if isinstance(val_list, list):
        for i in range(0, len(val_list)):
            new_num = d1.get(val_list[i], missing_default)
            val_list[i] = new_num
            d2[key] = val_list

print(d2) results in:
{596005: [inf], 4321416: [6, 1], 5802640: [inf, 2], 6031690: [inf, 2, 9, 1, 5]}

CodePudding user response:

Try:

from math import inf

d3 = {k: [d1[v] for v in lst] for k, lst in d2.items()}
print(d3)

Prints:

{596005: [inf], 4321416: [6, 1], 5802640: [inf, 2], 6031690: [inf, 2, 9, 1, 5]}

If you want to modify d2:

for lst in d2.values():
    lst[:] = (d1[v] for v in lst)

CodePudding user response:

You can try

d3 = {}
for k in d2:
    d3[k] = [d1[i] for i in d2[k]]
  • Related