好的,我想尝试过滤传递给我的列表/字典并使其“清洁”一些,因为其中有一些值需要摆脱。
那么,如果它看起来像这样:
"records": [{"key1": "AAA", "key2": "BBB", "key3": "CCC", "key4": "AAA"...}]
我怎样可以快速简便地遍历所有内容,并将所有"AAA"的值替换为"XXX"之类的值?
重点是速度和资源,因为这些列表可能很长,我不希望这个过程消耗太多时间。
好的,我想尝试过滤传递给我的列表/字典并使其“清洁”一些,因为其中有一些值需要摆脱。
那么,如果它看起来像这样:
"records": [{"key1": "AAA", "key2": "BBB", "key3": "CCC", "key4": "AAA"...}]
我怎样可以快速简便地遍历所有内容,并将所有"AAA"的值替换为"XXX"之类的值?
重点是速度和资源,因为这些列表可能很长,我不希望这个过程消耗太多时间。
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'}]}
dic = root['records'][0]
for i, j in dic.items(): # use iteritems in py2k
if j == 'AAA':
dic[i] = 'xxx'
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'}]}