替换Python列表/字典中的值?

时间:2009-07-02 20:29:29

标签: python list dictionary replace

好的,我正在尝试过滤传递给我的列表/字典并稍微“清理”一下,因为其中有一些我需要摆脱的值。

所以,如果它看起来像这样:

"records": [{"key1": "AAA", "key2": "BBB", "key3": "CCC", "key4": "AAA"...}]

我如何快速轻松地完成所有操作并将所有“AAA”值替换为“XXX”?

重点是速度和资源,因为这些可能是长列表,我不希望这个过程消耗太多时间。

3 个答案:

答案 0 :(得分:28)

DATA = {"records": [{"key1": "AAA", "key2": "BBB", "key3": "CCC", "key4": "AAA"}]}

for name, datalist in DATA.iteritems():  # Or items() in Python 3.x
    for datadict in datalist:
        for key, value in datadict.items():
            if value == "AAA":
                datadict[key] = "XXX"

print (DATA)
# Prints {'records': [{'key3': 'CCC', 'key2': 'BBB', 'key1': 'XXX', 'key4': 'XXX'}]}

答案 1 :(得分:10)

dic = root['records'][0]
for i, j in dic.items():       # use iteritems in py2k
    if j == 'AAA':
        dic[i] = 'xxx'

答案 2 :(得分:0)

就我而言,在字典理解中使用 if/else 比上述答案快得多。在下文中,我为您的用例提供了一个通用示例:

DATA = {"records_0": [{"key1": "AAA", "key2": "BBB", "key3": "CCC", "key4": "AAA"},
                      {"key1": "AAA", "key2": "BBB", "key3": "CCC", "key4": "AAA"}],
        "records_1": [{"key1": "AAA", "key2": "BBB", "key3": "CCC", "key4": "AAA"}]}

Replaced_DATA = {k:[
{k_0:v_0 if v_0!='AAA' else 'XXX' for k_0,v_0 in v_.items()} for v_ in v] for k,v in DATA.items()}

输出如下:

Replaced_DATA
Out[1]. {'records_0': [{'key1': 'XXX', 'key2': 'BBB', 'key3': 'CCC', 'key4': 'XXX'}, 
                       {'key1': 'XXX', 'key2': 'BBB', 'key3': 'CCC', 'key4': 'XXX'}],
         'records_1': [{'key1': 'XXX', 'key2': 'BBB', 'key3': 'CCC', 'key4': 'XXX'}]}