替换Python列表/字典中的值? [英] Replacing values in a Python list/dictionary?

查看:1195
本文介绍了替换Python列表/字典中的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我正在尝试过滤传递给我的列表/字典,并对其进行清理",因为其中有些特定的值我需要删除.

Ok, I am trying to filter a list/dictionary passed to me and "clean" it up a bit, as there are certain values in it that I need to get rid of.

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

So, if it's looking like this:

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

我该如何快速,轻松地完成所有操作,并将"AAA"的所有值替换为"XXX"?

How would I quickly and easily run through it all and replace all values of "AAA" with something like "XXX"?

重点在于速度和资源,因为这些可能很长,我不希望此过程浪费太多时间.

Focus is on speed and resources, as these may be long lists and I don't want this process to consume too much time.

推荐答案

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'}]}

这篇关于替换Python列表/字典中的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆