У меня есть такой вложенный словарь

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']
2
Brian Zheng 14 Апр 2019 в 05:22

2 ответа

Лучший ответ

Вопрос немного расплывчат, но такое решение может сработать. Это решение напечатает ваш стиль вывода для всех значений, которые не являются вложенными dict. Если значение для ключа имеет тип 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']
1
Error - Syntactical Remorse 14 Апр 2019 в 02:45

Вы можете попробовать вот так.

Предложение . Создайте функцию и используйте возможность многократного использования (функциональный подход), и это лучший способ (вы также можете использовать подход ООП ). Здесь я только что попытался удовлетворить потребность.

Если позднее вы выберете ООП , вы можете немного взглянуть на https://stackoverflow.com/a / 55671535/6615163 и попытайтесь понять (если вы новичок в ООП , иначе это нормально).

Здесь я попытался добавить Last_Name (то есть все ключи), если вы хотите только First_Name, то вы можете поместить условный оператор в inner (3-й) цикл и прекратить пропускать добавление к списку.

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']
1
hygull 14 Апр 2019 в 14:03