在遍历包含嵌套字典和列表的字典列表时,如何选择特定值?

时间:2019-03-15 17:10:51

标签: python json dictionary

在遍历包含嵌套字典和列表的字典列表时,我试图获取特定值。

这大致就是我导入的json数据的样子(简体)。这是带有嵌套词典和嵌套列表的词典列表。

# What a single dictionary looks like prettified

[{ 'a':'1',
'b':'2',
'c':'3',
'd':{ 'ab':'12',
      'cd':'34',
      'ef':'56'},
'e':['test', 'list'],
'f':'etc...'
}]

# What the list of dictionaries looks like

dict_list = [{ 'a':'1', 'b':'2', 'c':'3', 'd':{ 'ab':'12','cd':'34', 'ef':'56'}, 'e':['test', 'list'], 'f':'etc...'}, { 'a':'2', 'b':'3', 'c':'4', 'd':{ 'ab':'23','cd':'45', 'ef':'67'}, 'e':['test2', 'list2'], 'f':'etcx2...'},{},........,{}]

这是我最初拥有的代码,仅迭代字典列表。

for dic in dict_list:
    for val in dic.values():
        if not isinstance(val, dict):
            print(val)
        else:    
            for val2 in val.values():
                print (val2)

上面我原始代码中的打印语句只是为了向我展示从字典列表中提取的内容。我想要做的是声明要从顶级词典和二级词典和列表中获取的值。

以下是我正在寻找的输出示例。

列表中每个顶级词典的第一个键的值。

top_level_dict_key1 = ['1','2']

第2级词典的所有值。

level2_dic = ['12', '34', '56', '23', '45', '67']

或特定值。在这种情况下,每个嵌套字典中第一个键的值

level2_dict = ['12', '23']

嵌套列表中第二个键的值

level2_list = ['test', 'test2']

希望这很清楚。我会尽力澄清您是否也需要我。

1 个答案:

答案 0 :(得分:0)

对于Python 3.6 dictionaries happen to be ordered的特定实现,但是依靠这种行为是不好的。除非有序询问,否则询问某物的“第一要素”是没有意义的,因此第一步是到read the JSON into an OrderedDict

然后,这只是仔细记账的问题。例如

import json                                                                     
from collections import OrderedDict                                             

dict_list = '[{ "a":"1", "b":"2", "c":"3", "d":{ "ab":"12","cd":"34", "ef":"56"}, "e":["test", "list"], "f":"etc..."}, { "a":"2", "b":"3", "c":"4", "d":{ "ab":"23"    ,"cd":"45", "ef":"67"}, "e":["test2", "list2"], "f":"etcx2..."}]'

dict_list = json.loads(dict_list, object_pairs_hook=OrderedDict)    
top_level_dict_key1 = []
level2_dic = []
level2_dict = []
level2_list = []
for dictionary in dict_list:
    top_level_dict_key1.append(list(dictionary.values())[0])
    for value in dictionary.values():
        if isinstance(value, OrderedDict):
            level2_dic.extend(list(value.values()))
            level2_dict.append(list(value.values())[0])
        elif isinstance(value, list):
            level2_list.append(value[0])

print(top_level_dict_key1)
print(level2_dic)
print(level2_dict)
print(level2_list)

输出:

['1', '2']
['12', '34', '56', '23', '45', '67']
['12', '23']
['test', 'test2']

(这可能不是最惯用的Python 3代码。当我不那么累的时候,我会做一些更好的编辑。)

相关问题