Python搜索嵌套字典中的键/值

3

我有一个像这样的嵌套字典

profile = {
    "Person":{
        "name":{
            "First_Name":["John"], 
            "Last_Name":['Doe']
        }
    }, 
    "Object":{
        "name":{
            "First_Name":['John'], 
            "Last_Name":['Doe']
        }
    }
}

我不知道如何编写代码来打印查找“First_Name”和“John”的步骤,并确定它是键还是值。在嵌套字典中可能会有多个相同的值,我想要它们全部显示。例如:
First_Name is a key and is located in profile['Person']['name']['First_Name']
John is a value and is located in profile['Person']['name']['First_Name']
First_Name is a key and is located in profile['Object']['name']['First_Name']
John is a value and is located in profile['Object']['name']['First_Name']

你是否只需要“First_Name”的名字和值? - Error - Syntactical Remorse
2个回答

1
这个问题有点含糊,但是像这样的解决方案可能有效。此解决方案将打印所有非嵌套字典的值的输出样式。如果键的值是字典类型,则该函数将递归,直到找到不嵌套的值以进行打印。
def print_nested_dict(nested_dict, name, prior_keys=[]):
    for key, value in nested_dict.items():
        # current_key_path is a list of each key we used to get here
        current_key_path = prior_keys + [key]
        # Convert that key path to a string
        key_path_str = ''.join('[\'{}\']'.format(key) for key in current_key_path)

        # If the value is a dict then recurse
        if isinstance(value, dict):
            print_nested_dict(value, name, current_key_path)
        else:
            # Else lets print the key and value for this value
            print("{} is a key and is located in {}{}".format(key, name, key_path_str))
            print("{} is a value and is located in {}{}".format(value, name, key_path_str))

print_nested_dict(profile, "profile")

输出:

First_Name is a key and is located in profile['Person']['name']['First_Name']
['John'] is a value and is located in profile['Person']['name']['First_Name']
Last_Name is a key and is located in profile['Person']['name']['Last_Name']
['Doe'] is a value and is located in profile['Person']['name']['Last_Name']
First_Name is a key and is located in profile['Object']['name']['First_Name']
['John'] is a value and is located in profile['Object']['name']['First_Name']
Last_Name is a key and is located in profile['Object']['name']['Last_Name']
['Doe'] is a value and is located in profile['Object']['name']['Last_Name']

你的意思是什么?它将打印该值的路径,从而给出嵌套的级别。 - Error - Syntactical Remorse

1
你可以尝试这样做。
建议:创建一个函数并实现可重用性(函数式方法),这是最好的方法(您也可以使用面向对象编程方法)。在这里,我只是试图满足需求。
如果您以后选择面向对象编程,可以稍微看一下https://stackoverflow.com/a/55671535/6615163,并尝试获得想法(如果您是OOP新手,则可以这样做)。
在这里,我尝试添加Last_Name(即所有键),如果您只想要First_Name,则可以在inner(第三个)循环内放置条件语句,并停止跳过添加到列表中。
import json

profile = {
    "Person":{
        "name":{
            "First_Name":["John"], 
            "Last_Name":['Doe']
        }
    }, 
    "Object":{
        "name":{
            "First_Name":['John'], 
            "Last_Name":['Doe']
        }
    }
}

# START
messages = []
for key1 in profile:
    for key2 in profile[key1]:
        for key3 in profile[key1][key2]:
            message = "{0} is a {1} and is located in profile['{2}']['{3}']['{4}']"
            messages.append(message.format(key3, 'key', key1, key2, key3))
            messages.append(message.format(profile[key1][key2][key3][0], 'value', key1, key2, key3))

# --- Pretty print the list `messages` (indentation 4) ---
print(json.dumps(messages, indent=4))
# [
#     "First_Name is a key and is located in profile['Person']['name']['First_Name']",
#     "John is a value and is located in profile['Person']['name']['First_Name']",
#     "Last_Name is a key and is located in profile['Person']['name']['Last_Name']",
#     "Doe is a value and is located in profile['Person']['name']['Last_Name']",
#     "First_Name is a key and is located in profile['Object']['name']['First_Name']",
#     "John is a value and is located in profile['Object']['name']['First_Name']",
#     "Last_Name is a key and is located in profile['Object']['name']['Last_Name']",
#     "Doe is a value and is located in profile['Object']['name']['Last_Name']"
# ]


# --- As a string ---
print('\n'.join(messages))
# First_Name is a key and is located in profile['Person']['name']['First_Name']
# John is a value and is located in profile['Person']['name']['First_Name']
# Last_Name is a key and is located in profile['Person']['name']['Last_Name']
# Doe is a value and is located in profile['Person']['name']['Last_Name']
# First_Name is a key and is located in profile['Object']['name']['First_Name']
# John is a value and is located in profile['Object']['name']['First_Name']
# Last_Name is a key and is located in profile['Object']['name']['Last_Name']
# Doe is a value and is located in profile['Object']['name']['Last_Name']

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接