简体   繁体   English

如何在字典列表中迭代嵌套字典?

[英]How do I iterate through nested dictionaries in a list of dictionaries?

Still new to Python and need a little help here. 对Python来说还是新手,需要一些帮助。 I've found some answers for iterating through a list of dictionaries but not for nested dictionaries in a list of dictionaries. 我已经找到了一些用于迭代字典列表的答案,但不是针对字典列表中的嵌套字典。

Here is the a rough structure of a single dictionary within the dictionary list 这是字典列表中单个字典的粗略结构

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



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

That's more or less what I am looking at although there are some keys with lists as values instead of a dictionary but I don't think I need to worry about them right now although code that would catch those would be great. 这或多或少是我所看到的,虽然有一些键列表作为值而不是字典,但我不认为我现在需要担心它们,尽管可以捕获它们的代码会很棒。

Here is what I have so far which does a great job of iterating through the json and returning all the values for each 'high level' key. 到目前为止,我所做的就是迭代json并返回每个“高级”键的所有值。

import ujson as json

with open('test.json', 'r') as f:
    json_text = f.read()

dict_list = json.loads(json_text)

for dic in dict_list:
    for val in dic.values():
        print(val)

Here is the first set of values that are returned when that loop runs 这是该循环运行时返回的第一组值

1
2
3
{'ab':'12','cd':'34','ef':'56'}
4
etc...

What I need to be able to do pick specific values from the top level and go one level deeper and grab specific values in that nested dictionary and append them to a list(s). 我需要能够从顶层选择特定值并更深入一级并在该嵌套字典中获取特定值并将它们附加到列表中。 I'm sure I am missing a simple solution. 我确定我错过了一个简单的解决方案。 Maybe I'm looking at multiple loops? 也许我在看多个循环?

How about checking for the instance type using isinstance (of course only works for one level deeper). 如何使用isinstance检查实例类型(当然只适用于更深层次)。 Might not be the best way though 可能不是最好的方式

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)

# 1
# 2
# 3
# 12
# 34
# 56
# 4
# etc...
# 2
# 3

Following the ducktype style encouraged with Python, just guess everything has a .values member, and catch it if they do not: 遵循Python鼓励的ducktype风格,只是猜测所有内容都有一个.values成员,如果不这样做就抓住它:

import ujson as json

with open('test.json', 'r') as f:
    json_text = f.read()

dict_list = json.loads(json_text)

for dic in dict_list:
    for val in dic.values():
        try:
            for l2_val in val.values():
                print(l2_val)
        except AttributeError:
            print(val)

Bazingaa's solution would be faster if inner dictionaries are expected to be rare. 如果预期内部词典很少, Bazingaa的解决方案会更快。

Of course, any more "deep" and you would need some recursion probably: 当然,任何更“深”,你可能需要一些递归:

def print_dict(d):
    for val in d.values():
       try:
           print_dict(val)
        except AttributeError:
           print(val)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM