Home > Software engineering >  create 2 dictionaries from comparing the values of other 2 dictionaries
create 2 dictionaries from comparing the values of other 2 dictionaries

Time:09-29

I have two dictionaries, the original and the new one.

orig = {5: 10558, 33: 9297, 23: 5280, 
        26: 4507, 20: 3912, 8: 3746,
        18: 3265, 19: 3236, 22: 1560,
        32: 1091, 25: 958, 31: 878,
        21: 735, 4: 617, 2: 469,
        27: 302, 11: 292, 28: 239,
        10: 186, 14: 175, 29: 165,
        16: 144, 3: 120, 1: 119,
        7: 104, 17: 94, 9: 94, 
        6: 89, 0: 77, 13: 69,
        12: 56, 15: 46, 30: 41,
        24: 41}

new_dict = {5: 7391, 33: 9297, 23: 5280, 
            26: 4507, 20: 3912,
            8: 3746, 18: 4848, 
            19: 4819, 22: 2615,
            32: 2146, 25: 2013,
            31: 1933, 21: 1790, 
            4: 1672, 2: 1524, 
            27: 1357, 11: 1347,
            28: 1294, 10: 1241,
            14: 1230, 29: 1220, 
            16: 1199, 3: 1175, 
            1: 1174, 7: 1159, 
            17: 1149, 9: 1149, 
            6: 1144, 0: 1132,
            13: 1124, 12: 1111,
            15: 1101, 30: 1096, 24: 1096}

Now, I want to compare the 2 dictionaries and see which values changed to higher values and which values changed to lower values and create 2 different dicts.

The dict down will also contain the values the haven't changed.

So, create :

up ={18: 4848,
     19: 4819, 22: 2615,
     32: 2146, 25: 2013,
     31: 1933, 21: 1790, 
     4: 1672, 2: 1524, 
     27: 1357, 11: 1347,
     28: 1294, 10: 1241,
     14: 1230, 29: 1220, 
     16: 1199, 3: 1175, 
     1: 1174, 7: 1159, 
     17: 1149, 9: 1149, 
     6: 1144, 0: 1132,
     13: 1124, 12: 1111,
     15: 1101, 30: 1096, 24: 1096
}

down = {5: 10558, 
        33: 9297,
        23: 5280, 
        26: 4507,
        20: 3912,
        8: 3746
}

CodePudding user response:

You can use a simple loop, compare the values for each key and assign to the correct output:

up = {}
down = {}
for k,v in new_dict.items():
    if v>orig[k]:
        up[k] = v
    else:
        down[k] = orig[k]

NB. assuming that orig and new_dict have the same keys.

output:

# up
{18: 4848, 19: 4819, 22: 2615, 32: 2146, 25: 2013, 31: 1933, 21: 1790,
 4: 1672, 2: 1524, 27: 1357, 11: 1347, 28: 1294, 10: 1241, 14: 1230,
 29: 1220, 16: 1199, 3: 1175, 1: 1174, 7: 1159, 17: 1149, 9: 1149,
 6: 1144, 0: 1132, 13: 1124, 12: 1111, 15: 1101, 30: 1096, 24: 1096}

# down
{5: 10558, 33: 9297, 23: 5280, 26: 4507, 20: 3912, 8: 3746}
  • Related