[英]Looping through a list nested in a dictionary
我有一个由JSON结果组成的python字典。 该词典包含一个嵌套词典,该嵌套词典包含一个嵌套列表,该列表包含一个嵌套词典。 还在我这儿? 这是一个例子:
{'hits':{'results':[{'key1':'value1',
'key2':'value2',
'key3':{'sub_key':'sub_value'}},
{'key1':'value3',
'key2':'value4',
'key3':{'sub_key':'sub_value2'}}
]}}
我想从字典中得到的是sub_vale
每个sub_key
并将其存储在不同的列表。 无论我尝试什么,我都会不断出错。
这是我最后一次尝试:
inner_list=mydict['hits']['results']#This is the list of the inner_dicts
index = 0
for x in inner_list:
new_dict[index] = x[u'sub_key']
index = index + 1
print new_dict
它打印了前几个结果,然后开始返回原始词典中的所有内容。 我无法解决这个问题。 如果用print
语句替换new_dict[index]
行,它将完美地打印到屏幕上。 确实需要一些输入!
for x in inner_list:
print x[u'sub_key']
x
是字典
在for x in ...
的第一次迭代for x in ...
x={'key1':'value1',
'key2':'value2',
'key3':{'sub_key':'sub_value'}},
请注意, x
没有键sub_key
,而在x['key3']['sub_key']
>>> dic={'hits':{'results':[{'key1':'value1',
'key2':'value2',
'key3':{'sub_key':'sub_value'}},
{'key1':'value3',
'key2':'value4',
'key3':{'sub_key':'sub_value2'}}
]}}
>>> inner_list=dic['hits']['results']
>>> [x[y]['sub_key'] for x in inner_list for y in x if isinstance(x[y],dict)]
['sub_value', 'sub_value2']
如果您确定是key3
始终包含内部dict
,则:
>>> [x['key3']['sub_key'] for x in inner_list]
['sub_value', 'sub_value2']
不使用List comprehensions
:
>>> lis=[]
>>> for x in inner_list:
for y in x:
if isinstance(x[y],dict):
lis.append(x[y]['sub_key'])
>>> lis
['sub_value', 'sub_value2']
经过一些假设:
[e['key3']['sub_key'] for e in x['hits']['results']]
更改每个实例:
for e in x['hits']['results']:
e['key3']['sub_key'] = 1
索引错误来自new_dict[index]
,其中index
大于new_dict
的大小。
应该考虑列表理解。 通常情况下会更好,但是可以帮助您理解它是如何循环工作的。 试试这个吧。
new_list = []
for x in inner_list:
new_list.append(x[u'sub_key'])
print new_list
如果要坚持使用dict,但使用index作为键,请尝试以下操作:
index = 0
new_dict = {}
for x in inner_list:
new_dict[index] = x[u'sub_key']
index = index + 1
print new_dict
好的,根据您在下面的评论,我认为这就是您想要的。
inner_list=mydict['hits']['results']#This is the list of the inner_dicts
new_dict = {}
for x in inner_list:
new_dict[x['key2']] = x['key3']['sub_key']
print new_dict
您忘记了嵌套级别。
for x in inner_list:
for y in x:
if isinstance(x[y], dict) and 'sub_key' in x[y]:
new_dict.append( x[y]['sub_key'] )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.