Python 字典替换值

我有一本词典,里面有20000多个词条,目前只有一个独特的单词,以及这个单词在原文中被使用的次数(但丁的意大利语《神曲》)。

我想通过所有条目替换的价值与实际的定义,因为我发现他们。有没有一种简单的方法来遍历那些以数字作为值的关键字,以便替换(正如我所研究的意义) ?

字典开头是:

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

一种应用程序,将建议一个关键字来研究和定义。

536068 次浏览

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

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)

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'}

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'}
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

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)