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.
解决方案
Here is a function that will find your key and replace your value.
current_dict = {'corse': 378, 'cielo': 209, 'mute': 16}
print(current_dict)
def replace_value_with_definition(key_to_find, definition):
for key in current_dict.keys():
if key == key_to_find:
current_dict[key] = definition
replace_value_with_definition('corse', 'Definition of "corse"')
print(current_dict)
The output is:
{'corse': 378, 'cielo': 209, 'mute': 16}
{'corse': 'Definition of "corse"', 'cielo': 209, 'mute': 16}
If you find it is taking too long to loop through your dictionary try a generator function:
def gen_replace_value_with_definition(key_to_find, definition):
for key in current_dict.keys():
if key == key_to_find:
current_dict[key] = definition
yield True
yield False
found = False
while not found:
found = next(gen_replace_value_with_definition('corse', 'Definition of "corse" via generator'))
print(current_dict)
Output:
{'corse': 'Definition of "corse" via generator', 'cielo': 209, 'mute': 16}