简体   繁体   English

Python字典替换值

[英]Python dictionary replace values

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).我有一本包含 20 000 多个条目的字典,目前只有唯一的单词和该单词在源文本中使用的次数(但丁的意大利神曲)。

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.一种应用程序,它会建议一个关键字来研究和定义。

via dict.update() function通过 dict.update() 函数

In case you need a declarative solution, you can use dict.update() to change values in a dict.如果您需要声明式解决方案,您可以使用dict.update()更改 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:Python 3.5 开始,您还可以为此使用字典解包

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:Python 3.9开始,您还可以在字典上使用合并运算符

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

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:如果您遍历字典,您将获得键,因此假设您的字典位于名为data的变量中,并且您有一些获取定义的函数find_definition() ,您可以执行以下操作:

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

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:您可以使用下面的代码将dic0的值正确地更改为dic0to1而不必担心字典中的索引:

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

Now you have:现在你有:

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

Just had to do something similar.只需要做类似的事情。 My approach for sanitizing data for python based on Sadra Sabouri's answer:我根据Sadra Sabouri的回答为python清理数据的方法:

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)
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这会将 key1: value1 替换为 key1: change

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}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM