how to check every dictionary is perfect in list , python

Question:

I have a data set as below


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


and I have a data is a list of dictionaries like

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


and I found some of dictionaries are not perfectly have keys about ‘a’,’b’,’c’.

How do I check and fill the key is not existing

Asked By: runRyan

||

Answers:

You could try something like this:

# 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)

OUTPUT:

tmp_dict1 is missing key: c
tmp_dict3 is missing key: b
Answered By: ScottC

You can compare the keys in the dictionary with a set containing all the expected keys.

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

I think you want this.

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)

Output:

[{'a': 1, 'c': None, 'b': None}, {'b': 2, 'a': None, 'c': None}, {'c': 3, 'a': None, 'b': None}]
Answered By: Syrenthia
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.