Python Dictionary替换值并保存在dict中

jxn*_*jxn 2 python dictionary

我的字典值是应该'|x'在每个术语结束时具有的字符串.一些字符串包含许多术语,它们由a分隔space.

我试图删除没有的值中的术语,'|x'但字典没有保存新值.

d={'food': u'burger|x fries|x soda pie|x', 'transport': u'bus|x', 'animal': u'cat|x'}

for k,v in d.iteritems():
    for t in v.split(' '):
        if '|x' in v:
            v=v.replace(t,'')
Run Code Online (Sandbox Code Playgroud)

输出:

d
{'food': u'burger|x fries|x soda pie|x', 'animal': u'cat|x', 'transport': u'bus|x'}
Run Code Online (Sandbox Code Playgroud)

输出我想:

{'food': u'burger|x fries|x pie|x', 'animal': u'cat|x', 'transport': u'bus|x'}
Run Code Online (Sandbox Code Playgroud)

为什么没有取代价值?

Mos*_*oye 5

您只是创建一个新字符串而不是更新dict中的值.

您可以使用字典理解删除这些项目:

d = {'food': u'burger|x fries|x soda pie|x', 'transport': u'bus|x', 'animal': u'cat|x'}
d = {k: ' '.join(i for i in v.split() if i.endswith('|x')) for k, v in d.iteritems()}
print d
# {'food': u'burger|x fries|x pie|x', 'transport': u'bus|x', 'animal': u'cat|x'}
Run Code Online (Sandbox Code Playgroud)

请注意,split()可以split(' ')在此上下文中替换.