93.3k views
1 vote
Write a function named is_sub_dict that accepts two dictionaries from strings to strings as its parameters and returns True if every key in the first dictionary is also contained in the second dictionary and maps to the same value in the second dictionary. For example, given the dictionaries below, map1 is a sub-dict of map2, so the call of is_sub_dict(map1, map2) would return True. The order of the parameters does matter, so the call of is_sub_dict(map2, map1) would return False.

User Phonix
by
3.8k points

2 Answers

10 votes

Final answer:

The function is_sub_dict checks if one dictionary is a subset of another by comparing each key-value pair; it returns True if all key-value pairs in the first dictionary match those in the second dictionary.

Step-by-step explanation:

The function is_sub_dict you are asked to write should check whether one dictionary is a subset of another. The function compares each key-value pair in the first dictionary to the corresponding key-value pair in the second.

To implement this function in Python, you can iterate over each item in the first dictionary and verify if the key is present in the second dictionary and if the associated value is the same. Here is a sample implementation:

def is_sub_dict(map1, map2):
for key, value in map1.items():
if key not in map2 or map2[key] != value:
return False
return True

This function will return True if all key-value pairs in map1 are present in map2 with the same associations, and False otherwise.

User Camilo Martin
by
4.0k points
5 votes

def is_sub_dict(dict1, dict2):

one = dict1.keys()

two = dict2.keys()

for x in one:

if x in two:

if dict1[x] == dict2[x]:

pass

else:

return False

else:

return False

return True

I wrote the code in python 3.8. I hope this helps.

User Antonio Madonna
by
4.8k points