Python find value in nested dictionary

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

def iterate_all(iterable, returned="key"):
"""Returns an iterator that returns all keys or values
of a (nested) iterable.
Arguments:
- iterable: <list> or <dictionary>
- returned: <string> "key" or "value"
Returns:
- <iterator>
"""
if isinstance(iterable, dict):
for key, value in iterable.items():
if returned == "key":
yield key
elif returned == "value":
if not (isinstance(value, dict) or isinstance(value, list)):
yield value
else:
raise ValueError("'returned' keyword only accepts 'key' or 'value'.")
for ret in iterate_all(value, returned=returned):
yield ret
elif isinstance(iterable, list):
for el in iterable:
for ret in iterate_all(el, returned=returned):
yield ret

In Python3 we can build a simple generator to get all values from a nested dictionary. See below simple example code for it:-

def get_values(d):
    for v in d.values():
        if isinstance(v, dict):
            yield from get_values(v)
        else:
            yield v


a = {4: 1, 6: 2, 7: {8: 3, 9: 4, 5: {10: 5}, 2: 6, 6: {2: 7, 1: 8}}}

print(list(get_values(a)))

Output:

Python find value in nested dictionary

Get all keys of a nested dictionary

Here is code that would print all team members:

Liverpool = {
    'Keepers': {'Loris Karius': 1, 'Simon Mignolet': 2, 'Alex Manninger': 3},
    'Defenders': {'Nathaniel Clyne': 3, 'Dejan Lovren': 4, 'Joel Matip': 5, 'Alberto Moreno': 6, 'Ragnar Klavan': 7,
                  'Joe Gomez': 8, 'Mamadou Sakho': 9}
}


for k, v in Liverpool.items():
    for k1, v1 in v.items():
        print(k1)

Output:

Python find value in nested dictionary

Retrieve list of values from nested dictionaries

Iterates through the elements of the list and checks the type of each element based on the ‘id‘ and ‘children‘ naming convention.

mylist = [
    {u'id': 5650,
     u'children': [
         {u'id': 4635},
         {u'id': 5648}
     ]},
    {u'id': 67,
     u'children': [
         {u'id': 77}
     ]}
]


def extract_id_values(mylist):
    ids_to_return_list = []

    for element in mylist:
        for key, value in element.items():
            if 'id' == key:
                ids_to_return_list.append(value)
            if 'children' == key:
                for children_elem in value:
                    if 'id' in children_elem:
                        ids_to_return_list.append(children_elem['id'])
    return ids_to_return_list


print(extract_id_values(mylist))

Output: [5650, 4635, 5648, 67, 77]

Using list comprehension + values() + keys()

test_dict = {'Gfg': {"a": 7, "b": 9, "c": 12},
             'is': {"a": 15, "b": 19, "c": 20},
             'best': {"a": 5, "b": 10, "c": 2}}

# initializing key
key = "c"

# using keys() and values() to extract values
res = [sub[key] for sub in test_dict.values() if key in sub.keys()]

print(res)

Output: [12, 20, 2]

Using list comprehension + items()

test_dict = {'Gfg': {"a": 7, "b": 9, "c": 12},
             'is': {"a": 15, "b": 19, "c": 20},
             'best': {"a": 5, "b": 10, "c": 2}}

# initializing key
key = "a"

# using item() to extract key value pair as whole
res = [val[key] for keys, val in test_dict.items() if key in val]

print(res)

Output: [7, 15, 5]

Source: stackoverflow.com

Do comment if you have any doubts and suggestions on this Python dictionary list topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Python find value in nested dictionary

Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.

How do you get a value from a nested dictionary Python?

Access Values using get() Another way to access value(s) in a nested dictionary ( employees ) is to use the dict. get() method. This method returns the value for a specified key. If the specified key does not exist, the get() method returns None (preventing a KeyError ).

How do you iterate through a nested dictionary in Python?

Iterate over all values of a nested dictionary in python For a normal dictionary, we can just call the items() function of dictionary to get an iterable sequence of all key-value pairs.

How do you find the values of a key in a list of dictionaries in Python?

Use a list comprehension to find the values of a key in a list of dictionaries. Use the list comprehension syntax [dict[key] for dict in list_of_dicts] to get a list containing the corresponding value for each occurrence of key in the list of dictionaries list_of_dicts .

How do you find the value of the dictionary?

You can use the get() method of the dictionary ( dict ) to get any default value without an error if the key does not exist. Specify the key as the first argument. The corresponding value is returned if the key exists, and None is returned if the key does not exist.