假设有多个字典,它们的键并不一样,现在需要让每个字典的键一样,补全缺失的键,值填充为None
def fill_missing_keys(dict_list):
# 找出所有的keys
all_keys = set().union(*(d.keys() for d in dict_list))
# 遍历每一个字典,如果缺少某个key,则用None填充
result = [{key: d.get(key, None) for key in all_keys} for d in dict_list]
return result
input_data = [
{"key2": "value2", "key3": "value3"},
{"key1": "value1", "key3": "value3"},
{"key1": "value1", "key2": "value2"},
]
output_data = fill_missing_keys(input_data)
print(output_data)
输出
[{'key2': 'value2', 'key3': 'value3', 'key1': None},
{'key2': None, 'key3': 'value3', 'key1': 'value1'},
{'key2': 'value2', 'key3': None, 'key1': 'value1'}]