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

标签 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 的所有实例?

最佳答案

您只需循环浏览列表即可:

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

od 中的 key 首先测试成员资格;仅当 key 之前存在时才会更新。

关于python - 用Python中的值更新字典列表中所有匹配的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24589539/

相关文章:

Python单元测试检查函数调用参数

java - 将字符串转换为另一个字符串

c++ - 分配时 unordered_map 更改的顺序

list - 在 Pandas 中替换每个单元格的多个值

python - 将单索引数据框添加到多索引数据框、Pandas、Python

python - 从 VBA 调用 Python (Winwrap)

python - 检查字典键和值

python - 将字符串转换为日期时间python

python - 将字节转换为 Int 时出错 (Python 2.7)

Python 记录集中的多线程