Stuck searching nested dictionary

Hi there,

I could really use some help if possible please? I need to search a nested dictionary for 2 values without using any helpers etc.

cars = {‘1’: {‘make’: ‘ford’, ‘model’: ‘escort’}, ‘2’: {‘make’: ‘ford’, ‘model’: ‘focus’}}

for example, I would want to search for make = ford and model = focus and get the key value of 2 returned.

Can anyone help please?

Many thanks,

John

The code will depend on the specifics about your dictionary. Does every value have both the keys 'make' and 'model'? Is it possible for a value to have more keys than just those two? Can the dictionary contain more than 1 value or no values with a given make and model? If so, how should you handle these cases?

I’ll provide some example code for the case where every value has both the keys 'make’ and 'model', it is possible for a value to contain keys other than these two, and you want to find just the first occurrence of a value matching a given make and model.

def find_make_and_model(d, make, model):
    """Let d be a dictionary whose values are all dictionaries containing keys
    'make' and 'model'. Return the key corresponding to a value v such that
    v['make'] == make and v['model'] == model, or None if no such value was
    found."""
    for k, v in d.items():
        if v['make'] == make and v['model'] == model:
            return k
    return None

To search a dictionary by value, you can loop over the dict
keys and values together:

target = {'make': 'Ford', 'model': 'Focus'}
for key, value in cars.items():
    if value == target:
        print(key)
        break

The break keyword exits the loop.