【发布时间】:2018-08-07 06:38:58
【问题描述】:
我得到一个嵌套字典如下,它会在输入字典中的第一个键时返回第三个键
tree = {"Luke" : {"Darth Vader" : {"The Chancellor"}},
"Neal" : {"Les" : {"Joseph"}},
"George" : {"Fred" : {"Mickey"}},
"Robert" : {"Tim" : {"Michael"}},
"Juan" : {"Hunter" : {"Thompson"}}}
check_con = input("Enter your Name")
for fi_name,fi_second in tree.items():
if check_con in fi_name:
for fi_third,fi_fourth in fi_second.items():
print(fi_fourth)
感觉步骤有点多,有没有其他办法呢?
注意
【问题讨论】:
-
你的意思是如果你给“卢克”你想返回“总理”?
-
@VikasDamodar,是的
-
使用
fi_second = tree[check_con]。或者fi_second = tree.get(check_con)如果不能保证check_con存在。 -
我使用字典使它变得简单,即使它可以使用单个元组,或者列表对我来说没问题
-
.get(key[, default])在这里可能会有所帮助。
标签: python python-3.x dictionary nested