我從文件中讀取數據這樣的檢索單個項目:如何從嵌套的字典在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天,我該怎麼辦呢? 或者是否有一種更簡單的方法來保存數據以供將來在程序中參考?
意識到'dict_.items()'是一個列表不是字典。現在我改變了它,所以我將它存儲爲一個字典而不是列表,它似乎正在使用@Sven Marnach的解決方案的一部分在 – Scott