I am trying to figure out how to compare two dictionaries having different number of keys. For instance, here are two dictionaries:
person = {'name': 'John', 'birthYear': 1995, 'month': 1}
time = {'birthYear': 1995, 'month': 1}
I want to write code that if the second(birthYear) and third(month) key in person matches the first(birthYear) and second(month) key in time, the program will print out the name for the person (or in comparison just call it true). Is there a way to do so? I am pretty new to Python.
CodePudding user response:
Try something like:
person = {'name': 'John', 'birthYear': 1995, 'month': 1}
time = {'birthYear': 1995, 'month': 1}
if all(person[key] == time[key] for key in ['birthYear', 'month']):
print(person['name'])
CodePudding user response:
Sure there is: try
if person['birthYear'] == time['birthYear'] and person['month'] == time['month']:
print(person['name'])
Just use an if statement to check both conditions and print the results if they both pass the test
you can also nest the conditional statements like this:
if person['birthYear'] == time['birthYear']: # this must be true
if person['month'] == time['month']: # and this must be true
print(person['name']) # for this to print