检索嵌套数据信息

时间:2016-10-13 15:57:14

标签: python dictionary nested

下面是一本字典,我想知道如何从这样的嵌套数据(字典初级)中检索这些信息: 打印Joe的工作,Foster的出生年份,Maria的第一个孩子Maria的奖励数量,Maria的最后一个奖项,数据中所有人的年龄(以年为单位)(不适用于儿童) ),以及数据中所有人的子女数量。

我想知道如何格式化代码以检索此类信息。其中一些例子会有所帮助。

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"]
    },
}

1 个答案:

答案 0 :(得分:2)

以下是一些例子:

# 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)))