我正在检查字典中的密钥,如果它包含space
删除它。
def query_combination(sentence,mydict):
for key in mydict.keys():
if key == 'key':
pass
else:
print 'key is : ',key
if " " in key:
temp = key
key = key.replace(' ',"")
print 'new key : ',key
sentence = sentence.replace(temp ,key)
print 'new sentence : ',sentence
print mydict
mydict = {'films': {'match': ['Space', 'Movie', 'six', 'two', 'one']}, u'Popeye Doyle': {'score': 100, 'match': [u'People', 'heaven', 'released']}}
sentence ='What films featured the character Popeye Doyle'
combination = query_combination(sentence,mydict)
我无法将新密钥值动态更改为mydict
。任何建议都很明显
答案 0 :(得分:1)
如果从字典中获取字符串,然后更改它并创建一个新字符串,字典将不会知道它;您可以在字典中添加新条目并删除旧条目:
if " " in key:
newkey = key.replace(' ',"")
mydict[newkey] = mydict[key]
del mydict[key]
print 'new key : ', newkey
答案 1 :(得分:1)
你可以试试这个
def query_combination(sentence,mydict):
for key in mydict.iterkeys():
if " " in key:
temp = key
mydict[key.replace(" ","")] = mydict[key] # create new key
del mydict[key] # delete old key
sentence = sentence.replace(temp ,key)
一行中的另一个解决方案是
mydict[key.replace(" ","")] = mydict.pop(key)
答案 2 :(得分:0)
key = key.replace(' ',"")
不影响字典中的实际密钥,它正在更改该密钥的副本。您需要使用新密钥将值添加到字典中并删除旧密钥。这是一种方法:
def query_combination(sentence, mydict):
for old_key, new_key in [(key, key.replace(' ', '')) for key in mydict if ' ' in key]:
mydict[new_key] = mydict.pop(old_key)
sentence = sentence.replace(old_key, new_key)
但请注意,您要替换字符串sentence
中的密钥,但sentence
是函数query_combination()
的本地密钥,因此外部范围sentence
不受影响更换。我不确定这是否是您希望代码执行的操作,但如果是,您只需从函数中返回修订后的sentence
,或将其作为项目包含在字典中。
鉴于您的函数实际上没有更新sentence
,您可以将整个函数简化为单纯的字典理解:
>>> mydict = {'films': {'match': ['Space', 'Movie', 'six', 'two', 'one']}, u'Popeye Doyle': {'score': 100, 'match': [u'People', 'heaven', 'released']}}
>>> mydict = {key.replace(' ', '') : value for key, value in mydict.items()}
>>> mydict
{'films': {'match': ['Space', 'Movie', 'six', 'two', 'one']}, u'PopeyeDoyle': {'score': 100, 'match': [u'People', 'heaven', 'released']}}