Normality - 1 month ago 12
Python Question

Retrieving Nested Data Info

Below is a dictionary and I would like to know how I can retrieve this information from such nested data (Beginner at dictionaries) :
Prints Joe's job, the year of birth of Foster,the number of awards of Maria,the first child of Panos,the last award of Maria,the age (in years) of all people in the data (not for children), and the number of children for all people in the data.

I would just like to know how to format the code to retrieve such information. An example of a few of them would be helpful.

``````data = {
"Foster": {
"Job": "Professor",
"YOB": 1965,
"Children": ["Hannah"],
"Awards": ["Best Teacher 2014", "Best Researcher 2015"],
"Salary": 120000
},
"Joe": {
"Job": "Data Scientist",
"YOB": 1981,
"Salary": 200000
},
"Maria": {
"Job": "Software Engineer",
"YOB": 1993,
"Children": [],
"Awards": ["First place in Math Olympiad 2010","Valedictorian 2011", "Dean's List 2013"]
},
"Panos": {
"Job": "Professor",
"YOB": 1976,
"Children": ["Gregory", "Anna"]
},
}
``````

Here are few examples:

``````# joe's job
data["Joe"]["Job"]

#year of birth of Foster
data["Foster"]["YOB"]

#the number of awards of Maria
len(data["Maria"]["Awards"])

#the first child of Panos
data["Panos"]["Children"][0]

#the last award of Maria
data["Maria"]["Awards"][-1]

#the age (in years) of all people in the data,
current_year = 2016
for entry in data:
age = current_year - data[entry]["YOB"]
print(entry + " " +str(age))

#the number of children for all people in the data.
for entry in data:
children = data[entry].get("Children",[])
print(entry + " " +str(len(children)))
``````
Source (Stackoverflow)