替换Python字典中的值?

时间:2013-07-19 05:09:54

标签: python list dictionary

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

如何快速轻松地完成所有操作并替换" \ xef \ xbb \ xbfUser_ID"的所有值。用" User_ID"?

重点是速度和资源,因为这些可能是包含许多字典值的长列表。

1 个答案:

答案 0 :(得分:2)

以下情况如何?

# 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”键,这很奇怪(字典中有唯一的键)。