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



我有这样的嵌套字典

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

这个问题有点模糊,但这样的解决方案可能会奏效。此解决方案将为未嵌套dict s 的所有值打印输出样式。 如果键的值是dict类型,则该函数将递归,直到找到未嵌套打印的值。

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

你可以这样尝试。

建议:创建一个函数并实现可重用性(函数方法(,这是最好的方法(您也可以使用 OOP 方法(。在这里,我只是试图满足这一需要。

如果您以后选择OOP,则可以稍微查看一下 https://stackoverflow.com/a/55671535/6615163 并尝试获得想法(如果您是OOP的新手,否则没关系(。

在这里,我尝试添加Last_Name(即所有键(,如果您只想First_Name那么您可以在 (3rd( 循环中放置一个条件语句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']

最新更新