My data looks like this:
data = {'Shop1': {'Fruit': {2021: 5},
'Veggies': {2021: 10}},
'Shop2': {'Veggies': {2021: 6}},
'Shop3': {'Veggies': {2021: 4}},
'Shop4': {'Meat': {2021: 8},
'Veggies': {2021: 9},
'Cheese': {2021: 6},
'Sweets': {2021: 9},
'Drinks': {2021: 15}}}}
Shop1
, Shop2
, Shop3
and Shop4
... are my primary keys whereas Fruit, Veggies and other products are my nested keys. I'm trying to find a way to query this dictionary in order to display the list of shops with Veggies
AND without Fruit
. In this case, the result would be ['Shop2', 'Shop3', 'Shop4']
.
Any idea how to do that?
Use a simple list comprehension:
[k for k,d in data.items() if 'Veggies' in d and not 'Fruit' in d]
output: ['Shop2', 'Shop3', 'Shop4']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.