Reputation: 127
I'm having trouble searching if a key and corresponding value from one dictionary (stock) is in another dictionary (basket)
this is the error I receive:
File "C:/Users/mbbx2wc3/.spyder2-py3/temp.py", line 35, in <module>
if stock['10005'] in basket:
TypeError: unhashable type: 'dict'
And this is my code if you want to have a look. I have tried is stock[key] in basket. but this gives an error and I cannot think of an alternative to try.
Many thanks
stock = {
'10005' : {
'name' : 'Conference Pears Loose',
'price' : 2.00,
'unit' : 'kg',
'promotion' : None,
'group' : None,
'amount' : 1.550
},
'10013' : {
'name' : 'Emmental Slices 250G',
'price' : 1.75,
'unit' : 'pieces',
'promotion' : 'get2pay1',
'group' : None,
'amount' : 9
},
'10015' : {
'name' : 'Diced Beef 400G',
'price' : 4.50,
'unit' : 'pieces',
'promotion': 'get4pay3',
'group' : 4,
'amount' : 14
}}
basket = {}
if stock['10005'] in basket:
print("yay")
else:
print("noo")
Upvotes: 0
Views: 2101
Reputation: 895
import json
stock = {
'10005' : {
'name' : 'Conference Pears Loose',
'price' : 2.00,
'unit' : 'kg',
'promotion' : None,
'group' : None,
'amount' : 1.550
},
'10013' : {
'name' : 'Emmental Slices 250G',
'price' : 1.75,
'unit' : 'pieces',
'promotion' : 'get2pay1',
'group' : None,
'amount' : 9
},
'10015' : {
'name' : 'Diced Beef 400G',
'price' : 4.50,
'unit' : 'pieces',
'promotion': 'get4pay3',
'group' : 4,
'amount' : 14
}}
basket = {}
for item in stock.keys():
if item in basket.keys():
print("This key " + item + " is in basket")
else:
print("This key " + item + " is not in basket")
for item in stock.values():
if item in basket.values():
print("This value " + json.dumps(item) + " is in basket")
else:
print("This value " + json.dumps(item) + " is not in basket")
Upvotes: 0
Reputation: 1044
You can try something like this:
key = 'a key your are testing'
if basket.get(key, false) == stock[key]:
print('yes')
else:
print('no')
Upvotes: 0
Reputation: 311606
First of all, you can't test if something contains a dictionary. The error message TypeError: unhashable type: 'dict'
is basically telling you that; there are some details about that here.
You're probably going to need a two step process:
For example:
if '10005' in basket and basket['10005'] == stock['10005']:
print "Yup"
else:
print "Nope"
Upvotes: 0
Reputation: 5871
You are looking to see if the value of stock['10005'], which is some large dict, is also a key in basket.
https://docs.python.org/2/library/stdtypes.html#typesmapping
A dictionary’s keys are almost arbitrary values. Values that are not hashable, that is, values containing lists, dictionaries or other mutable types (that are compared by value rather than by object identity) may not be used as keys.
I think perhaps you want to see if '10005' in basket
Upvotes: 1
Reputation: 10789
Just use the key...
if '10005' in basket:
print("it's in basket")
elif '10005' in stock:
print("it's in stock")
else:
print("it's nowhere")
Upvotes: 1