Skip to content

Python get all values from nested dictionary | Example code

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

Get all values from nested dictionary

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 get all values from 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:

Get all keys of a 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]

Extract values of Particular Key in Nested Values

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.

1 thought on “Python get all values from nested dictionary | Example code”

  1. You have been really inspired me in programming. Thanks.
    Am having issues with nested dictionary where some of the values In the sub dict are list.Am to print out and count all the elements in these list.
    Eg d ={‘dict_1’ : {‘a’:5,’,b’:[‘bb’,’ffg’,’mmm’],’c’:’lb’},’dict_2′:{‘h’:23,’t’:[‘zzz’,’jkl’,’sas’,’yrx’]}}
    Expected output:
    bb
    ffg
    mmm
    zzz
    jkl
    sas
    yrx
    7

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading