在python中搜索字典中的特定键和值

时间:2016-11-06 18:02:11

标签: python python-3.x

dic = {"Name":"Test1","Age":"23"},{"Name":"Test2","Age":"24"},{"Name":"Test3","Age":"21"}

搜索Test3并打印21

2 个答案:

答案 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会将其视为tupledict个对象。我们来看看:

>>> 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