Windy71
Windy71

Reputation: 909

Pythonic way to check a dict has all the keys it should

I have some working code but wondered if there is a more pythonic way to code it.

Working code

mydict = {"a":77, "b":22}
wanted_dict_keys = ["a", "b", "c"]

# is each item of the wanted_dict_key present as a key in the dict
def all_keys_present(wanted_dict_keys, mydict):
    existing_keys = []
    keys_missing = []
    for k,v in mydict.items():
        existing_keys.append(k)
    #print(existing_keys)
    for key in wanted_dict_keys:
        if key not in existing_keys:
            keys_missing.append(key)
            #print("this key is not in the dict: ", key)
    return existing_keys, keys_missing

existing_keys, keys_missing = all_keys_present(wanted_dict_keys, mydict)
print('\n')
print("existing_keys : ", existing_keys)
print("keys_missing : ", keys_missing)

Upvotes: 1

Views: 110

Answers (5)

anjandash
anjandash

Reputation: 827

✅ Inline solution: to get both the existing_keys and missing_keys:

existing_keys = [k for k in wanted_dict_keys if k in mydict.keys()]
missing_keys  = [k for k in wanted_dict_keys if k not in mydict.keys()]

However, if you want to keep the same code structure:

mydict = {"a":77, "b":22}
wanted_dict_keys = ["a", "b", "c"]

def all_keys_present(wanted_dict_keys, mydict):    
    existing_keys = [k for k in wanted_dict_keys if k in mydict.keys()]
    missing_keys  = [k for k in wanted_dict_keys if k not in mydict.keys()]
    return existing_keys, missing_keys

existing_keys, missing_keys = all_keys_present(wanted_dict_keys, mydict)
print('\n')
print("existing_keys : ", existing_keys)
print("missing_keys  : ", missing_keys)

Upvotes: 2

Alain T.
Alain T.

Reputation: 42133

If it is ok to have more keys, then you can use the issubset() function after turning your list of keys into a set.

if set(wanted_dict_keys).issubset(mydict):
    print("all keys are present")
else:
    print("some keys are missing")

If you want to avoid the set conversion on every check, you should store your wanted_dict_keys as a set instead of a list.

Upvotes: 1

Daweo
Daweo

Reputation: 36680

You might use set arithmetic following way

mydict = {"a":77, "b":22}
wanted_dict_keys = ["a", "b", "c"]
missing = set(wanted_dict_keys).difference(mydict.keys())
print(missing)

output:

{'c'}

You might use such created missing in if statement, as empty set is considered False and all other True.

Upvotes: 3

C.Nivs
C.Nivs

Reputation: 13106

Use all:

mydict = {"a":77, "b":22}
wanted_dict_keys = ["a", "b", "c"]

if all(k in mydict for k in wanted_dict_keys):
    print("All there")
else:
    raise ValueError("Missing keys!")

Or if you want to be specific:

not_present = [k for k in wanted_dict_keys if k not in mydict]

if not_present:
    raise ValueError(f"Missing required keys {not_present}")
else:
    print(f"Got keys: {list(mydict)}")

Upvotes: 2

Epsi95
Epsi95

Reputation: 9047

mydict.keys() will give you all keys. And set will do the equality check.

mydict = {"a":77, "b":22}
wanted_dict_keys = ["a", "b", "c"]

if (set(mydict.keys()) == set(wanted_dict_keys)):
    print('all are present')
else:
    print('not all are present')
not all are present

Upvotes: 2

Related Questions