我有这样的嵌套字典
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
然后你可以在inner
(3rd)循环中放置一个条件语句并停止跳过列表的添加。
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']