[英]Iterating through list which is value of a dict
I have many sets of JSON data, each of which looks like this after being converted into dict:我有很多组JSON数据,每组转换成dict后是这样的:
json_data =
{
"root":[
1,
2,
3
]
}
I want to iterate through the list [1,2,3]
with this:我想用这个遍历列表
[1,2,3]
:
for value in json_data.values():
print(value)
I expect to get this output:我希望得到这个 output:
1
2
3
But I get this: 1
2
3
但我明白了:
[1,2,3]
What should I change in the code?我应该在代码中更改什么? Thanks !
谢谢 !
dict.keys()
or dict.values()
will give us dict_values([[1, 2, 3]])
dict.keys()
或 dict.values dict.values()
会给我们dict_values([[1, 2, 3]])
So iterating through this like所以像这样迭代
for value in json_data.values():
print(value)
will return us.将返回我们。 Note:
json_data.values()[0]
will return an error TypeError: 'dict_values' object is not subscriptable
注意:
json_data.values()[0]
会返回错误TypeError: 'dict_values' object is not subscriptable
[1, 2, 3]
You have three options here.你在这里有三个选择。
Option1 use your example but iterate twice Option1使用您的示例,但迭代两次
for value in json_data.values():
for lst in value:
print(last)
Option2 if you know the key you can use .get()
or dict['key']
选项2 ,如果您知道可以使用
.get()
或dict['key']
for value in json_data['root']:
print(value)
for value in json_data.get('root'):
print(value)
Option3选项3
for value in json_data.values():
print(*value)
This will give you 1 2 3
Now of course there are many more options but these are what I could think of.这将为您提供
1 2 3
现在当然还有更多选择,但这些是我能想到的。
You probably want to use dict.items()
:您可能想使用
dict.items()
:
json_data = {
"root": [1, 2, 3]
}
for key, values in json_data.items():
print(key, values)
for value in values:
print(value)
You can use the list
key word so that you can use the indices of the json_data.values()
您可以使用
list
关键字,以便可以使用json_data.values()
的索引
for value in list(json_data.values())[0]:
print(value)
this will return: (in your example case)这将返回:(在您的示例中)
1
2
3
To do this for all the keys in json_data, you can do:要对 json_data 中的所有键执行此操作,您可以执行以下操作:
for index in range(len(json_data.values())):
for value in list(json_data.values())[index]:
print(value)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.