lord stock
lord stock

Reputation: 1201

Python compare Dictionary Key on condition

I have the following python dictionary which I made sorted in order to find their difference

k={0: 2, 1: 1, 3: 2, 4: 1, 5: 1, 6: 1}

Now I want to compare dictionary keys in such a way that, if the dictionary key difference is equal to 1, I want to add two values of dictionaries. I tried the approach of next and Iter but I am not getting the expected Item sadly.

The dictionary key ranges from 0-100 only

required output if possible in array [3,3,2,2] i.e difference of 0 and 1 is 1 so value of 0 and 1 is 3(sum of 1 and 0 value) and same for 3,4

Upvotes: 1

Views: 98

Answers (1)

BlackAnubis7
BlackAnubis7

Reputation: 268

If I understand the question correctly:

k={0: 2, 4: 1, 1: 1, 6: 1, 3: 2, 5: 1}
keys = sorted(k.keys())  # [0, 1, 3, 4, 5, 6]

result = []
for i in range(1, len(keys)):
    if keys[i] - keys[i-1] == 1:
        result.append(k[keys[i]] + k[keys[i-1]])

print(result)  # [3, 3, 2, 2]

Please remember, that if not all dictionary keys are always numbers, above code will not work - you'd have to catch TypeError in keys = sorted(k.keys()) line

Upvotes: 5

Related Questions