使用重复索引循环嵌套字典

时间:2014-10-16 14:05:52

标签: python loops dictionary

我尝试设置带有标记的嵌套字典,并在此嵌套字典上循环某个命令。

dictionary = {"item 1":{"subitem 1":"one of one","subitem 2":"two of one"},"item 2":{"subitem 1":"one of two", "subitem 2":"two of two"}}

第一轮"的输出" (或第一个循环)应该是:

some.command{input:one of one, output: two of one}

第二轮"

的输出
some.command{input:one of two, output:two of two}

等等。我真的想使用标记,只需循环遍历所有二级字典上的条目就不会(因为命令必须忽略条目)。循环应该如下所示:

for x in dictionary.itervalues():
    for y in x.itervalues():
        some.command(input: y["subitem 1], output: y["subitem 2"])

这种方法不起作用,因为我无法通过索引访问所选值。如果我更换" some.command"使用" print y [" subitem 1"]我收到错误" TypeError:字符串索引必须是整数,而不是str"。

我做错了什么?我是以错误的方式或我的循环命令或两者设置我的字典吗?

1 个答案:

答案 0 :(得分:1)

x已经是你的嵌套字典了;你不需要内循环。我使用x来澄清循环迭代的内容,而不是使用nested_dict(一个相当无意义的名称):

for nested_dict in dictionary.itervalues():
    some.command(input=nested_dict["subitem 1"], output=nested_dict["subitem 2"])

然后,你的内循环正在循环那些嵌套字典的值; y绑定到"one of one",然后绑定"two of one"等。尝试使用y['some string']尝试将索引应用于这些字符串。

此外,这些for循环中没有任何地方使用索引。 Python for循环直接在项目上迭代 。您告诉Python循环dictionary.itervalues(),因此每个nested_dict都绑定到dictionary的每个值。没有使用指数。