95

I have a dictionary with 20 000 plus entries with at the moment simply the unique word and the number of times the word was used in the source text (Dante's Divine Comedy in Italian).

I would like to work through all entries replacing the value with an actual definition as I find them. Is there a simple way to iterate through the keywords that have as a value a number in order to replace (as I research the meaning)?

The dictionary starts:

{'corse': 378, 'cielo,': 209, 'mute;': 16, 'torre,': 11, 'corsa': 53, 'assessin': 21, 'corso': 417, 'Tolomea': 21}  # etc.

Sort of an application that will suggest a keyword to research and define.

1
  • I ended up packing a fresh dictionary. It works, but it's really inefficient. dict feels like a mess.
    – Kermit
    Commented Oct 8, 2020 at 11:52

6 Answers 6

136

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'}
1
  • the key1 in key1='value1' is not a variable. Even if your key1 is a variable, it interprets as a string 'key1'. Commented May 31, 2023 at 21:34
93

You cannot select on specific values (or types of values). You'd 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 I'd go with the reverse index:

from collections import defaultdict

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

Now you can look up keys by value:

for key in reverse[value]:
    inputdict[key] = newvalue
4
  • 1
    In Python 2, if iterating over a large dictionary, use iteritems() instead of items() so that the entire dictionary contents aren't loaded into memory. (This doesn't matter for Python 3 since items() basically does what iteritems() did in Python 2.)
    – nofinator
    Commented Jan 5, 2017 at 16:47
  • 3
    @nofinator: in Python 2, you use iteritems() to prevent the creation of a new list list with len(dictionary) tuples referencing the key-value pairs in the dictionary (rather a waste when only iterating). The dictionary contents themselves are always loaded into memory. Not that this applies here, as the question is tagged Python 3 :-) Commented Jan 5, 2017 at 17:21
  • @MartijnPieters can we have the same setting to retrieve the old value somehow? Like if .update() returned the old value, it would have saved me a step of saving the old value and then replacing in case I want to do that Commented Mar 8, 2018 at 9:53
  • 1
    @VivekKalyanarangan: not sure what you are asking; the question here was about finding a key for a given value, and then using that key to replace something somewhere else. I think you are asking if you can get the old value for a given key, and at the same time put in the new value? There is not, just use two statements: old = d.get(key) in case a missing key is not an error, or use old = d[key] otherwise, and then use d[key] = new. Commented Mar 8, 2018 at 21:07
10

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

I think this may help you solve your issue.

Imagine you have a dictionary like this:

dic0 = {0:"CL1", 1:"CL2", 2:"CL3"}

And you want to change values by this one:

dic0to1 = {"CL1":"Unknown1", "CL2":"Unknown2", "CL3":"Unknown3"}

You can use code bellow to change values of dic0 properly respected to dic0to1 without worrying yourself about indexes in dictionary:

for x, y in dic0.items():
    dic0[x] = dic0to1[y]

Now you have:

>>> dic0
{0: 'Unknown1', 1: 'Unknown2', 2: 'Unknown3'}
0

Just had to do something similar. My approach for sanitizing data for python based on Sadra Sabouri's answer:

def sanitize(value):
    if str(value) == 'false':
        return False
    elif str(value) == 'true':
        return True
    elif str(value) == 'null':
        return None
    return value

for k,v in some_dict.items():
        some_dict[k] = sanitize(v)
-3
data = {key1: value1, key2: value2, key3: value3}

for key in data:
   if key == key1:
       data[key1] = change
       print(data)

this will replace key1: value1 to key1: change

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.