如何检查每个字典是完美的列表,python



我有一个如下的数据集


tmp_dict = {
'a': ?,
'b': ?,
'c': ?,
}

我有一个data是一个字典列表,比如

tmp_list = [tmp_dict1, tmp_dict2, tmp_dict3....]

,我发现一些字典并没有很好地标注a, b, c。

如何检查和填充键不存在

你可以尝试这样做:

# List of keys to look for in each dictionary
dict_keys = ['a','b','c']
# Generate the dictionaries for demonstration purposes only
tmp_dict1 = {'a':[1,2,3], 'b':[4,5,6]}
tmp_dict2 = {'a':[7,8,9], 'b':[10,11,12], 'c':[13,14,15]}
tmp_dict3 = {'a':[16,17,18], 'c':[19,20,21]}
# Add the dictionaries to a list as per OP instructions
tmp_list = [tmp_dict1, tmp_dict2, tmp_dict3]
#--------------------------------------------------------
# Check for missing keys in each dict. 
# Print the dict name and keys missing.
# -------------------------------------------------------
for i, dct in enumerate(tmp_list, start=1):
for k in dict_keys:
if dct.get(k) == None:
print(f"tmp_dict{i} is missing key:", k)

输出:

tmp_dict1 is missing key: c
tmp_dict3 is missing key: b

我想你想要这个。

tmp_dict = {'a':1, 'b': 2, 'c':3}
default_keys = tmp_dict.keys()
tmp_list = [{'a': 1}, {'b': 2,}, {'c': 3}]
for t in tmp_list:
current_dict = t.keys()
if default_keys - current_dict:
t.update({diff: None for diff in list(default_keys-current_dict)})
print(tmp_list)

输出:

[{'a': 1, 'c': None, 'b': None}, {'b': 2, 'a': None, 'c': None}, {'c': 3, 'a': None, 'b': None}]

您可以将字典中的键与包含所有期望键的集合进行比较。

for d in tmp_list:
if set(d) != {'a', 'b', 'c'}:
print(d)

相关内容

  • 没有找到相关文章

最新更新