检查文本中的单词,如果它与字典键匹配,则添加到该键的值

时间:2019-09-30 21:52:06

标签: python dictionary data-structures

我将文本存储在像这样的字符串变量中

r= '4"3/4 cutting head on location as part of the contract with NOV'

我有这样的字典

d={'4"3/4':0}

我想检查键值是否与字符串中的任何数据匹配,如果为true,则将一个数字添加到所提到的键的值中

2 个答案:

答案 0 :(得分:1)

您可以制作更新的字典:

d = {key: value + 1 if key in r else value
   for key, value in d.items()}

答案 1 :(得分:0)

for key,value in d.items():
    if key in r:
        d[key]=value+1

希望这会有所帮助。