Scott
Scott

Reputation: 3

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? Or is there an easier way to hold the data for future reference within the program?

Upvotes: 0

Views: 575

Answers (1)

Sven Marnach
Sven Marnach

Reputation: 602355

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"]:

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

Upvotes: 2

Related Questions