gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 18:08:31 24 4
gpt4 key购买 nike

我正在尝试设置一个带有索引的嵌套字典,并在该嵌套字典上循环某个命令。

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"])

这在某种程度上不起作用,因为我无法通过索引访问选定的值。如果我用“print y[”subitem 1”]替换“some.command”,我会收到错误“TypeError:字符串索引必须是整数,而不是str”。

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

最佳答案

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

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

然后,您的内部循环正在循环这些嵌套字典的值; y 绑定(bind)到 “one of one”,然后绑定(bind)到 “two of one”,等等。尝试使用 y['some string'] 试图对这些字符串应用索引。

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

关于python - 循环使用重复索引的嵌套字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26406488/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com