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

时间:2011-11-09 21:33:17

标签: python dictionary

我正在阅读一个包含以下数据的文件:

{"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"}

我将数据放入字典中,然后根据某些条件评估字典,并将字典放入另一个字典中,如下所示:

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

现在如果我只是想知道孩子们在第4天做了什么,我该怎么做? 或者是否有更简单的方法来保存数据以供将来在程序中参考?

1 个答案:

答案 0 :(得分:2)

您可以使用字典将工作日名称映射到数字来简化代码。要提取第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"]