python 字典元素替换_Python字典替换值

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}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值