Python dictionary replace values

Python dictionary replace values

You cannot select on specific values (or types of values). Youd either make a reverse index (map numbers back to (lists of) keys) or you have to loop through all values every time.

If you are processing numbers in arbitrary order anyway, you may as well loop through all items:

for key, value in inputdict.items():
    # do something with value
    inputdict[key] = newvalue

otherwise Id go with the reverse index:

from collections import defaultdict

reverse = defaultdict(list)
for key, value in inputdict.items():

Now you can look up keys by value:

for key in reverse[value]:
    inputdict[key] = newvalue

via dict.update() function

In case you need a declarative solution, you can use dict.update() to change values in a dict.

Either like this:

my_dict.update({key1: value1, key2: value2})

or like this:

my_dict.update(key1=value1, key2=value2)

via dictionary unpacking

Since Python 3.5 you can also use dictionary unpacking for this:

my_dict = { **my_dict, key1: value1, key2: value2}

Note: This creates a new dictionary.

via merge operator or update operator

Since Python 3.9 you can also use the merge operator on dictionaries:

my_dict = my_dict | {key1: value1, key2: value2}

Note: This creates a new dictionary.

Or you can use the update operator:

my_dict |= {key1: value1, key2: value2}

Python dictionary replace values

If you iterate over a dictionary you get the keys, so assuming your dictionary is in a variable called data and you have some function find_definition() which gets the definition, you can do something like the following:

for word in data:
    data[word] = find_definition(word)

Leave a Reply

Your email address will not be published. Required fields are marked *