下面的呢?
# Dictionaries with "\xef\xbb\xbfUser_ID'" in both keys and values:
group1 = [{"key1": "AAA", "\xef\xbb\xbfUser_ID'": "BBB", "key3": "CCC", "key4": "DDD"},
{"key1": "EEE", "key3": "FFF", "key4": "\xef\xbb\xbfUser_ID'", "key4": "HHH"},
{"key1": "AAA", "key3": "BBB", "\xef\xbb\xbfUser_ID'": "JJJ", "key4": "III"}]
for group_dict in group1:
# Fast key replacement (no test in for loop):
try:
group_dict['User_ID'] = group_dict.pop("\xef\xbb\xbfUser_ID'")
except KeyError:
pass
# Value replacement:
for (key, value) in group_dict.iteritems():
if value == "\xef\xbb\xbfUser_ID'":
group_dict[key] = 'User_ID'
print group1 # Cleaned up dictionaries
产量
[{'key3': 'CCC', 'key1': 'AAA', 'User_ID': 'BBB', 'key4': 'DDD'},
{'key3': 'FFF', 'key1': 'EEE', 'key4': 'HHH'},
{'key3': 'BBB', 'key1': 'AAA', 'User_ID': 'JJJ', 'key4': 'III'}]
这不会使用太多内存(除了新"User_ID"
字符串的内存),而且我想不出更快的方法。
请注意,您的第二个字典有两个“key4”键,这很奇怪(字典具有唯一的键)。