从字典中的列表中获取信息

时间:2017-06-28 09:59:03

标签: python list

我有下一个代码:

ind=[{'id':123,'name'='Andrew','universities':[{'country'=123,'state'=123}], school=[{'name'=Beliech,'state'=...}],'type'=[{}] }]

我需要在学校领域取名学校的名称,并在大学领域与国家说明将其添加到数据库中。我试图将list ind转换为字典(info = ind [0]),然后获取信息,但我遇到了问题,该学校也是一个列表,所以我不能使用ind['school']['name']。大学和学校不是一成不变的,它们可以相互替代,并保持在开始/结束/中间。我该如何获取此信息?

2 个答案:

答案 0 :(得分:0)

import pandas
ind=[{'id':123,'name':'Andrew','universities':[{'country':123,'state':1234}], 'school':[{'name':"Beliech"}]}]
name_list = []
school_name_list = []
university_country_list = []
university_state_list = []
for i in range(len(ind)):
    name_list.append(ind[i]['name'])
    school_name_list.append(ind[i]['school'][0]['name'])
    university_country_list.append(ind[i]['universities'][0]['country'])
    university_state_list.append(ind[i]['universities'][0]['state'])
Output = pandas.DataFrame({'Name':name_list,'School_Name':school_name_list,'University_Country':university_country_list,'University_State':university_state_list})

我对这个问题并不十分清楚。根据我的理解,这就是我能想到的

答案 1 :(得分:0)

我试着回答你,但实际上我无法理解一些观点。

ind = [{'id':123, 'name':'Andrew','universities':[{'country':123,'state':123}], 'school':[{'name':'Beliech','state':...}],'type':[{}]}]

list_dict = []
for index in range (0, len(ind[0]["school"])):
    new_dict = {
        "School_Name" :  ind[0]["school"][index]["name"],
        "University_Country": ind[0]["universities"][index]["country"],
        "University_State": ind[0]["universities"][index]["state"],
    }
    list_dict.append(new_dict)

我只是为每个学校创建一个字典,大学与之相关联。在您的示例中,Beliech学校与国家123和州123中的大学相关联。所有词典都存储在列表中。 我不知道这是不是你真正想要的。我希望如此。

请注意字典键。你把学校和Beliech写成两个变量而不是字符串。我认为这不是你想要的。

修改

我希望这将是你正在寻找的。如果没有,请尝试更准确,请:

ind = [{'id':123, 'name':'Andrew','universities':[{'country':123,'state':123}], 'school':[{'name':'Beliech','state':...}],'type':[{}]}]

user_name = input("Please, enter your name")

for index in range (0, len(ind)):
    if ind[index]["name"] == user_name:
        dict = ind[index]
        school_list = []
        for school in range(0, len(dict["school"])):
            school_list.append(dict["school"][school]["name"])
        university_list = []  # list of dictionary with all the info about a University
        universitycountry_list = []
        universitystate_list = []
        for uni in range(0, len(dict["universities"])):
            university_list.append(dict["universities"][uni])
            universitycountry_list.append(dict["universities"][uni]["country"])
            universitystate_list.append(dict["universities"][uni]["state"])
        found = True
        break
    else:
        found = False

if not found:
    print("The user {} is not in the Database".format(user_name))

# print(school_list)
# print(university_list)
# print(universitycountry_list)
# print(universitystate_list)