简体   繁体   English

如何从python中的嵌套字典中检索单个项目

[英]How to retrieve a single item from nested dictionary in python

I am reading from a file with data like this: 我正在读取一个包含如下数据的文件:

{"day" :"Monday", "alarm":"on", "kids":"School" , "work":"days"}
{"day" :"Tuesday", "alarm":"on", "kids":"School" , "work":"days"}
{"day" :"Wednesday", "alarm":"on", "kids":"School" , "work":"days"}
{"day" :"Thursday", "alarm":"on", "kids":"School" , "work":"nights"}
{"day" :"Friday", "alarm":"on", "kids":"School" , "work":"nights"}
{"day" :"Saturday", "alarm":"off", "kids":"Dance" , "work":"overtime"}
{"day" :"Sunday", "alarm":"off", "kids":"Soccer" , "work":"off"}

I am putting the data into an dictionary, then evaluating the dictionary for some condition and placing that dictionary into another dictionary like so: 我将数据放入字典,然后评估字典中的某些条件并将该字典放入另一个字典中,如下所示:

import ast
o=open('schedule.txt','rb')
day_={}
for lines in o:
    dict_={}
    dict_= ast.literal_eval(lines)
    if dict_['day']=='Monday':
        day_['1']=dict_.items()
    elif dict_['day']=='Tuesday':
        day_['2']=dict_.items()
    elif dict_['day']=='Wednesday':
        day_['3']=dict_.items()
    elif dict_['day']=='Thursday':
        day_['4']=dict_.items()
    elif dict_['day']=='Friday':
        day_['5']=dict_.items()
    elif dict_['day']=='Saturday':
        day_['6']=dict_.items()
    elif dict_['day']=='Sunday':
        day_['7']=dict_.items()
    else:
        print('there was an error')
o.close()
print day_.items()
#this seems to work properly

Now if I only want to find out what the kids are doing on day 4, how do I do this? 现在,如果我只是想知道孩子们在第4天做了什么,我该怎么做? Or is there an easier way to hold the data for future reference within the program? 或者是否有更简单的方法来保存数据以供将来在程序中参考?

You can simplify your code by using a dictionary to map weekday names to numbers. 您可以使用字典将工作日名称映射到数字来简化代码。 To extract the "kids" item of the record for day 4, you can use result[4]["kids"] : 要提取第4天记录的"kids"项目,您可以使用result[4]["kids"]

days = {"Monday": 1, "Tuesday": 2, "Wednesday": 3, "Thursday": 4,
        "Friday": 5, "Saturday": 6, "Sunday": 7}
result = {}
with open('schedule.txt', 'rb') as f:
    for line in f:
        d = ast.literal_eval(line)
        result[days[d["day"]]] = d
print result[4]["kids"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM