G
G
German2018-11-13 21:55:57
Python
German, 2018-11-13 21:55:57

How to return the value of a dictionary key that is in a nested dictionary?

I am writing a simple program in Python3, the following problem arose:
There is a json response:

{
    "response": [{
    "id": 11111,
    "first_name": "Blah-Blah",
    "last_name": "Lalalala",
    "city": {
        "id": 2,
        "title": "Санкт-Петербург"
        }
    }]
}

All this is decoded by the json.loads() function and is of type dict , a dictionary.
For example, I want to access the title, I could call it like this ["response"][0]["city"]["title"], but I know that only ["response"][0] will work 100%, the name of the field itself, for example title , is entered manually and may be different, there may also be several nested dictionaries, the task of the program is to find and get the value of the entered value, in this case title .

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Y
Yura Khlyan, 2018-11-14
@MAGistr_MTM

for response in content['response']:
   print(response.get('city', {}).get('title', ""))

J
Juhani Lahtinen, 2018-11-14
@nukler

Here's a dear link.
Find all occurences of a key in nested python dict...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question