Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtract 1 from all values in dictionary

I have a dictionary like the following:

dict = {'hi':1, 'hi2':2, 'lskdjf':3}

It continues like this for over a million values.

I want to convert this into a dictionary with a value starting at 0

For example, this is the desired output:

dict = {'hi':0, 'hi2':1, 'lskdjf':2}

How can this be done efficiently?

like image 925
Keshav M Avatar asked Nov 20 '25 15:11

Keshav M


1 Answers

You can either iterate over the dictionary to update it...

for k in dict_:
    dict_[k] -= 1

... or create a new dictionary with a dictionary comprehension.

new_dict = {k: v - 1 for k, v in dict_.items()}

In both cases note that I replaced your variable name by dict_ to avoid overwriting the built-in dict name.

like image 101
Olivier Melançon Avatar answered Nov 22 '25 06:11

Olivier Melançon