首页 > 解决方案 > 在字典中分隔空格 [Python]

问题描述

我正在编写一个索引程序并完成,但是当我得到某个单词的字典值时,我得到了这种字典:{'self evidence': 2} where I really want {'self': 2, 'evident': 2}

有没有办法做到这一点,删除字典值中的空格,分离键,然后复制与键关联的值?

感谢您的帮助,如果我能解决我的问题,请告诉我,对不起,如果它令人困惑。

标签: pythondictionary

解决方案


代码:

dic = {'self evident a b c': 2,"d e f":3}
result = {}
for k,v in dic.items():
    for new_key in k.split():
        result[new_key] = v
print(result)

结果:

{'self': 2, 'evident': 2, 'a': 2, 'b': 2, 'c': 2, 'd': 3, 'e': 3, 'f': 3}

推荐阅读