简体   繁体   中英

Get a dictionary having a specific key value pair from a complex dictionary

I hit a specific scenario where I want to get the dictionary which contains specific value out of a complex dictionary.

For example consider the below dictionary

a = {"tire1": {"source": "PEP","dest": "host1"},"tire6":{"source": "REP","dest":"host2"}}

If the value of dest host1 matches then the function should return {"tire1": {"source": "PEP","dest": "host1"} of type dictionary.

EDIT: If it matches multiple same values then it should returns multiple matching dictionary in a single dictionary

Thanks

You Can do something like this by using dictionary comprehension

final_dict = {key: value for key,value in a.items() if value["dest"] == "host1" }

You could define a function with a results list, iterate on the keys and values of dictionary a , append to the results list any values (sub-dictionaries) where the 'dest' key equals 'host1' , and then return the list of results.

def func(a: dict):
    results = []  # define a list of results to return
    for key, value in a.items():  # iterate on keys values
        if value['dest'] == 'host1': 
            results.append(a[key])  # append that sub-dict to the results

    return results

This would return:

result = func(a)
print(results)
----
{
    "tire1": 
        {
            "source": "PEP",
            "dest": "host1"
        }
}

You can simply write a loop to match the specified value. In your case, the code is following:

dicts = {"tire1": {"source": "PEP","dest": "host1"},"tire6":{"source": "REP","dest":"host2"}}
search_value = 'host1'
for key, values in dicts.items():
  for value in values.values():
    if value == search_value:
      print(f'The Key is {key} and', f'The dictionary are {values}')

This will return the matched dictionary with the key. The result will be:

The Key is tire1 and The dictionary are {'source': 'PEP', 'dest': 'host1'}

A more robust option could be:

a = {"tire1": {"source": "PEP", "dest": "host1"},
     "tire6": {"source": "REP", "dest": "host2"}}

result = {k: v for k, v in a.items() if v.get('dest') == 'host1'}

print(result)

...in case there are sub-dictionaries where the 'dest' key is absent

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM