dic = {"Name":"Test1","Age":"23"},{"Name":"Test2","Age":"24"},{"Name":"Test3","Age":"21"}
搜索Test3并打印21
答案 0 :(得分:2)
您可能希望您的词典位于列表中,如下所示:
dic = [{"Name":"Test1","Age":"23"},{"Name":"Test2","Age":"24"},{"Name":"Test3","Age":"21"}]
现在,我们可以找到值为“Test3”的Name
并打印Age
。
for d in dic:
if d["Name"] == "Test3":
print("Age is: " + d["Age"])
答案 1 :(得分:2)
根据您提供的语法,python会将其视为tuple
个dict
个对象。我们来看看:
>>> dic = {"Name":"Test1","Age":"23"},{"Name":"Test2","Age":"24"},{"Name":"Test3","Age":"21"}
>>> type(dic)
<type 'tuple'> # type as "tuple"
>>> dic # lets print the content
({'Age': '23', 'Name': 'Test1'}, {'Age': '24', 'Name': 'Test2'}, {'Age': '21', 'Name': 'Test3'})
# ^ All "dict" objects wrapped in `(...)`
您需要迭代tuple
(只要考虑迭代,类似到list
),并检查Name
值为Test3
。示例代码:
>>> for item in dic:
... if item["Name"] == "Test3":
... print(item["Age"])
...
21