Extract id's as a list from python dictionary

Viewed 533

I am trying to extract id's from a nested dictionary using python, However it runs error when I run the next code:

nested_dictionary = {
    "name": "field",
    "vacant": "capable",
    "employees": 
        {
            1: {"id": 1, "name": "Joe", "px": "px1"},
            2: {"id": 2, "name": "Mary", "px": "px2"},
            3: {"id": 3, "name": "George", "px": "px3"},
            4: {"id": 4, "name": "Louise", "px": "px4"},
            5: {"id": 5, "name": "Malcolm", "px": "px5"},
            6: {"id": 6, "name": "Reese", "px": "px6"},
        },
        "columns": 
        [
            "col1",
            "col2",
            "col3",
            "col4"
       
        ],
    "columns_2": 
        [
            "col5",
            "col6",
            "col7"
        ]
}


for p in nested_dictionary['employees']
    print('id:' + p['id'])

Console Output:

Type Error: i object is not subscriptable

Expected Output:

id: 1
id: 2
id: 3
id: 4
id: 5
id: 6

Is there any other way to accomplish this task?

1 Answers

You need to iterate over the values of the dictionary:

for p in nested_dictionary['employees'].values():
    print(f'id: {p["id"]}')

Output

id: 1
id: 2
id: 3
id: 4
id: 5
id: 6

Currently you are iterating over the keys. Also note that:

'id:' + p['id']

is an invalid operation because there are a string and int respectively. See the documentation on dictionaries for more information. Also this resource for looping techniques over a dictionary.

Related