[SOLVED] Reduce the key value of dictionary by one


This Content is from Stack Overflow. Question asked by Jack

Having a dictionary as below:

a_dict = {1: 'blue', 2: 'apple', 3: 'dog'}

need to reduce the key value by one and drop the blue value.

a_dict = {1: ‘apple’, 2: ‘dog’}


What you want to do is a bit strange (what is the real underlying goal?)

One option, assuming you want to keep the same order, and shift the values after blue to one key before:

l = list(a_dict.values())

d = dict(zip(a_dict, l))

Output: {1: 'apple', 2: 'dog'}

NB. In case of multiple ‘blue’, this would only remove the first one. To remove all:

d = dict(zip(a_dict, [v for v in a_dict.values() if v != 'blue']))

dropping the first value

If you already know that the value to drop if the first one:

out = dict(zip(a_dict, list(a_dict.values())[1:]))

Or, more efficient:

i = iter(a_dict.values())
next(i) # consume first value
out = dict(zip(a_dict, i))

This Question was asked in StackOverflow by Jack and Answered by mozway It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?