2011-11-09 203 views
0

我從文件中讀取數據這樣的檢索單個項目:如何從嵌套的字典在python

{"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天,我該怎麼辦呢? 或者是否有一種更簡單的方法來保存數據以供將來在程序中參考?

+0

意識到'dict_.items()'是一個列表不是字典。現在我改變了它,所以我將它存儲爲一個字典而不是列表,它似乎正在使用@Sven Marnach的解決方案的一部分在 – Scott

回答

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

以下@Scott:除非在「1」中有一些隱藏含義,否則「2 「,」3「......字符串,爲什麼不把星期幾的名字留在原地?就像在''結果[「星期四」] [「孩子們」]' – digitalarbeiter

+0

我喜歡你的映射這樣的日子的解決方案,但是這是一個簡單的例子,我一直在用來測試和處理一個不同的問題一個天氣腳本,我沒有這樣的地圖。在天氣腳本中,我使用的是日期而不是數字,我希望能夠獲得特定日期的信息。以同樣的方式工作,但這只是簡化。 – Scott

+0

OP中還有一個拼寫錯誤:Wedensday –