使用Python中的值更新字典列表中的所有匹配键

时间:2014-07-05 18:48:52

标签: python python-2.7 dictionary

key = 'take'
val = 5

dicts = [
    OrderedDict([
        (u'rt', 0), 
        (u'janoameezy', 0), 
        (u'calum', 0), 
        (u'is', 0), 
        (u'me', 0), 
        (u'whenever', 0), 
        (u'i', 0), 
        (u'take', 0), 
        (u'a', 0), 
        (u'selfie', 0), 
        (u'http', 0), 
        (u't', 0), 
        (u'co', 0), 
        (u'sxn68vta2a', 0)
    ]), 
    OrderedDict([
        (u'relax', 0), 
        (u'and', 0), 
        (u'take', 0), 
        (u'notes', 0), 
        (u'while', 0), 
        (u'i', 0), 
        (u'tokes', 0), 
        (u'of', 0), 
        (u'the', 0), 
        (u'marijuana', 0), 
        (u'smoke', 0)
    ])
]

如何用val替换所有key实例?

1 个答案:

答案 0 :(得分:2)

您只需遍历列表:

for od in dicts:
    if key in od:
        od[key] = val

首先对key in od成员资格进行测试;密钥只有在以前存在时才会更新。

相关问题