Home > Back-end >  Get a dictionary having a specific key value pair from a complex dictionary
Get a dictionary having a specific key value pair from a complex dictionary

Time:04-07

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

CodePudding user response:

You Can do something like this by using dictionary comprehension

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

CodePudding user response:

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"
        }
}

CodePudding user response:

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'}

  • Related