Home > Software design >  How to get key-value pair after computing the difference of consecutive key elements in dictionary
How to get key-value pair after computing the difference of consecutive key elements in dictionary

Time:10-25

I am working on dictionaries and lists. This is my input data.

{19: [[2, 1796]], 24: [[4, 1792]], 273: [[46, 1774]], 275: [[46, 1773]], 494: [[3, 1793]], 499: [[2, 1796]]}

I want to compute the differences of two consecutive key values. (first I compare 19, 24. Then I compare 273,275, and so on). If the difference is <= 5, then I want to get the key-value pair of the lowest key.

So, my output would look like this

{19: [[2, 1796]], 273: [[46, 1774]], 494: [[3, 1793]]}

I tried dictionary comprehension with lambda functions but got logical errors.

CodePudding user response:

You can achieve this with a few lines. Create a new empty dictionary and fill it in a loop while checking each time the difference between the keys:

dic = {19: [[2, 1796]], 24: [[4, 1792]], 273: [[46, 1774]], 275: [[46, 1773]], 494: [[3, 1793]], 499: [[2, 1796]]}

new_dic = dict()
for k,v in dic.items():
    if not(new_dic) or k-list(new_dic.keys())[-1] > 5:
        new_dic[k] = v

print(new_dic)

Output:

{19: [[2, 1796]], 273: [[46, 1774]], 494: [[3, 1793]]}
  • Related