-2

I have 2 dictionaries:

dict1 = {"Name":"x", "Surname":"y", "Age":30}

dict2 = {"Name":"x", "Surname":"y"}

I want a condition like this:

if dict2 in dict1:
    return True

If I run this code it returns:

TypeError: unhashable type: 'dict'

Solutions?

Matteo Bianchi
  • 434
  • 1
  • 4
  • 19

3 Answers3

2

You could do the following:

all(item in dict1.items() for item in dict2.items())

you will have to iterate on the dicts elements

David
  • 8,113
  • 2
  • 17
  • 36
2

This should work for you if you only want to check whether the keys are already present :

if all(key in dict1 for key in dict2):
    return True

If you want to check whether the values also match as well, try this :

if all(kv in dict1.items() for kv in dict2.items()):
    return True
Arkistarvh Kltzuonstev
  • 6,824
  • 7
  • 26
  • 56
1

You can do:

dict1 = {"Name": "Bob", "Surname": "Smith", "Age": 30}

dict2 = {"Name": "Bob", "Surname": "Smith"}

print(all(dict1[k] == v for k, v in dict2.items()))
funnydman
  • 9,083
  • 4
  • 40
  • 55