Home > Back-end >  Reduce the key value of dictionary by one
Reduce the key value of dictionary by one

Time:09-19

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.

output: a_dict = {1: 'apple', 2: 'dog'}

CodePudding user response:

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())
l.remove('blue')

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))

CodePudding user response:

Another solution, with := operator:

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

i = 0
a_dict = {i: v for v in a_dict.values() if v != "blue" and (i := i   1)}
print(a_dict)

Prints:

{1: 'apple', 2: 'dog'}
  • Related