从循环中返回字典

时间:2014-08-06 18:03:23

标签: python loops python-2.7 for-loop dictionary

我有一个循环,根据存储在列表中的星期几来创建字典。代码如下所示:

days_of_theweek = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]
day_count = 0
index_count = 0
hours = {}   

for i in days_of_theweek:
    if day_count == index_count:
        the_day = days_of_theweek[index_count]
        hours[the_day] = raw_input("  Enter the shift hours for " + str(the_day)+": ")                
        os.system('cls')
        day_count += 1
        index_count += 1
    return hours

问题是,运行此代码只返回循环中的第一次迭代{Monday : some int}。我知道这是因为它显然在一次迭代后停止循环后返回return语句。此外,我注意到删除return语句允许循环运行正常,但它在结束时返回no,这是不好的大声笑。我的问题是如何运行我的整个循环并返回完成的字典。

4 个答案:

答案 0 :(得分:1)

Python对缩进级别很敏感。将return hours语句移出for-loop

def get_hours():
    days_of_theweek = ["Monday", "Tuesday", "Wednesday", "Thursday",
                       "Friday", "Saturday", "Sunday"]
    hours = {}

    for the_day in days_of_theweek:
        prompt = "  Enter the shift hours for {}: ".format(the_day)
        hours[the_day] = int(raw_input(prompt))
        os.system('cls')
    return hours

有关清除该行的其他方法(从而避免os.system调用,请参阅(如何)Print in one line dynamically。)

答案 1 :(得分:0)

for i in days_of_theweek:
    if day_count == index_count:
        the_day = days_of_theweek[index_count]
        hours[the_day] = raw_input("  Enter the shift hours for " + str(the_day)+": ")                
        os.system('cls')
        day_count += 1
        index_count += 1
return hours # return outside the loop

答案 2 :(得分:0)

return语句没有正确缩进。它应与for语句处于同一级别。

答案 3 :(得分:0)

weekday = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]
dayHourDictionary = {}

for day in weekday:
   print "please enter the shift hours for", day ,":"
   shiftHours = input('')
   dayHourDictionary[day]=shiftHours



print dayHourDictionary