为什么这种循环字典的方法不起作用

时间:2015-07-17 13:56:37

标签: python dictionary

我在字典中有一本字典。我正在尝试返回最里面的字典,即带有键名称,教师等的字典。要循环我试过这个。

courses = {
'feb2012': { 'cs101': {'name': 'Building a Search Engine',
                       'teacher': 'Dave',
                       'assistant': 'Peter C.'},
             'cs373': {'name': 'Programming a Robotic Car',
                       'teacher': 'Sebastian',
                       'assistant': 'Andy'}},
    'jan2044': { 'cs001': {'name': 'Building a Quantum Holodeck',
                       'teacher': 'Dorina'},
           'cs003': {'name': 'Programming a Robotic Robotics Teacher',
                       'teacher': 'Jasper'},
                 }
}

for e in courses:
     for y in e:
         return courses[e][y]

控制台返回键错误,我做错了什么?

3 个答案:

答案 0 :(得分:5)

如果你这样做:

for e in courses:
    print e

您发现它打印"feb2012""jan2044" - 值为字符串

所以下一行的for y in e:会遍历这些字符串的字符

你的意思是

for e in cources:
    for y in cources[e]:
        return courses[e][y]

但是,因为你返回,你只会找到一个内部词典。我想知道这是不是你需要的。

要获得所有这些,其中一种方法可能是使用yield代替return 生成器

def get_inner(courses):
    for e in courses:
        for y in courses[e]:  # Aside, these variable names are horrible
            yield courses[e][y]

现在你可以使用for innerdict in get_inner(courses): ...循环播放它们。

但是有很多方法......

答案 1 :(得分:0)

for x in courses:                #Iterate through the outermost keys
    for y in courses[x]:         #Iterate through the second outer most keys
        return courses[x][y]:    #Return the innermost dictionary

答案 2 :(得分:0)

for k,v in courses.items():             #Iterates through Month/Year keys (feb2012, jan2014
    for k2,v2 in v.items():             #Iterates thought class identifer keys (cs101, cs373, cs001,cs003)
        for k3, v3 in v2.items():       #Iterates though class information (name, teacher, assistant)
            print('Semester: ' + k + '\tCourse: ' + k2 + '\tKey: ' + k3 + '\tValue: ' + v3) #Displays class information

输出:

Semester: feb2012   Course: cs101   Key: assistant  Value: Peter C.
Semester: feb2012   Course: cs101   Key: teacher    Value: Dave
Semester: feb2012   Course: cs101   Key: name   Value: Building a Search Engine
Semester: feb2012   Course: cs373   Key: assistant  Value: Andy
Semester: feb2012   Course: cs373   Key: teacher    Value: Sebastian
Semester: feb2012   Course: cs373   Key: name   Value: Programming a Robotic Car
Semester: jan2044   Course: cs001   Key: teacher    Value: Dorina
Semester: jan2044   Course: cs001   Key: name   Value: Building a Quantum Holodeck
Semester: jan2044   Course: cs003   Key: teacher    Value: Jasper
Semester: jan2044   Course: cs003   Key: name   Value: Programming a Robotic Robotics Teacher