说我有一本这样的字典:
profile = {'Person':{'name':['John'], 'Description':['smart']}}
我正在寻找一段代码来搜索“ John”和“ Description”,但不知道它们在嵌套字典中的位置。我也想在代码中打印出这样的内容:
John is located in the value of profile['Person']
Description is located in the key of profile['Person']
我该怎么做?任何帮助将不胜感激。谢谢
答案 0 :(得分:1)
了解如何iterate浏览嵌套词典。在Python字典中,items()方法用于返回带有所有带有值的字典键的列表。索引[]用于访问嵌套字典的元素
profile = {'Person':{'name':['John'], 'Description':['smart']},'Person1':{'name':['John1'], 'Description':['smart1']}}
for p_id, p_info in profile.items():
for key in p_info:
if p_info[key][0] == "John":
print(p_info[key][0],"is located in the value of profile['",p_id,"']")
if p_info[key][0] == "smart":
print(p_info[key][0],"is located in the value of profile['",p_id,"']")