Search code examples
pythonlistdictionarysublist

What's the fastest way to identify the 'name' of a dictionary that contains a specific key-value pair?


I'd like to identify the dictionary within the following list that contains the key-value pair 'Keya':'123a', which is ID1 in this case.

lst = {ID1:{'Keya':'123a','Keyb':456,'Keyc':789},ID2:{'Keya':'132a','Keyb':654,'Keyc':987},ID3:{'Keya':'5433a','Keyb':222,'Keyc':333},ID4:{'Keya':'444a','Keyb':777,'Keyc':666}}

It's safe to assume all dictionaries have the same key's, but have different values.

I currently have the following to identify which dictionary has the value '123a' for the key 'Keya', but is there a shorter and faster way?

    DictionaryNames = map(lambda Dict: str(Dict),lst)
    Dictionaries = [i[1] for i in lst.items()]
    Dictionaries = map(lambda Dict: str(Dict),Dictionaries) 

    Dict = filter(lambda item:'123a' in item,Dictionaries)
    val = DictionaryNames[Dictionaries.index(Dict[0])]
    return val

Solution

  • If you actually had a list of dictionaries, this would be:

    next(d for d in list_o_dicts if d[key]==value)
    

    Since you actually have a dictionary of dictionaries, and you want the key associated with the dictionary, it's:

    next(k for k, d in dict_o_dicts.items() if d[key]==value)
    

    This returns the first matching value. If you're absolutely sure there is exactly one, or if you don't care which you get if there are more than one, and if you're happy with a StopIteration exception if you were wrong and there isn't one, that's exactly what you want.

    If you need all matching values, just do the same with a list comprehension:

    [k for k, d in dict_o_dicts.items() if d[key]==value]
    

    That list can of course have 0, 1, or 17 values.