循环嵌套在字典中的列表

时间:2012-07-09 18:06:12

标签: python list dictionary for-loop

我有一个由JSON结果组成的python字典。该字典包含嵌套字典,其中包含嵌套列表,其中包含嵌套字典。还在我这儿?这是一个例子:

{'hits':{'results':[{'key1':'value1', 
                    'key2':'value2', 
                    'key3':{'sub_key':'sub_value'}},
                   {'key1':'value3',
                    'key2':'value4',
                    'key3':{'sub_key':'sub_value2'}}
                  ]}}

我想从字典中获取的是每个sub_vale的{​​{1}},并将其存储在不同的列表中。无论我尝试什么,我都会遇到错误。

这是我最后一次尝试:

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 语句替换new_dict[index]行,它会完美地打印到屏幕上。真的需要一些意见!

print

5 个答案:

答案 0 :(得分:1)

x是一本字典

for x in ...

的第一次迭代中
x={'key1':'value1', 
                'key2':'value2', 
                'key3':{'sub_key':'sub_value'}},

请注意sub_key中没有键x,而是x['key3']['sub_key']

答案 1 :(得分:1)

>>> 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']

答案 2 :(得分:1)

做出一些假设后:

[e['key3']['sub_key'] for e in x['hits']['results']]

要更改每个实例:

for e in x['hits']['results']:
 e['key3']['sub_key'] = 1

答案 3 :(得分: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 = 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

答案 4 :(得分:1)

你忘记了筑巢的程度。

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