首页 > 解决方案 > 从python中的字典创建字典

问题描述

text="we are in pakistan and love pakistan and olx"
dict1={"pakistan": "COUNTRY", "olx": "ORG"}

我需要匹配文本中的键,如果它存在将该单词的索引存储为新字典中的键,其中值应该与该特定单词的 dict1 中的值相同,例如输出应该是这样的:

dict2={[10:17]:"COUNTRY",[27:34]:"COUNTRY","[40:42]:"ORG"}

标签: pythonlistdictionarylist-comprehensiondictionary-comprehension

解决方案


首先,我必须解决您的预期结果,即具有不可散列的列表,因为字典的键是不可能的。见https://wiki.python.org/moin/DictionaryKeys

产生类似的方法是使用re 库

import re
text="we are in pakistan and love pakistan and olx"
dict1={"pakistan": "COUNTRY", "olx": "ORG"}
dict2 = {}
for key, value in dict1.items():
    matched_all = re.finditer(key,text)
    for matched in matched_all:
        dict2[matched.span()] = value
print(dict2)

这会给你:

{(10, 18): 'COUNTRY', (28, 36): 'COUNTRY', (41, 44): 'ORG'}

推荐阅读