0
"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”之类的东西?

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

4

1 回答 1

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

于 2013-07-19T05:17:31.367 回答