在python中打印字典的键值对

时间:2016-11-16 11:42:26

标签: python python-2.7

在这种情况下如何打印键值对:

a = [
{"name": "Tom", "age": 10},
{"name": "Mark", "age": 5},
{"name": "Pam", "age": 7}
]

search_name = 'Tom'

for i in a:
   for key in i:
      if (i[key] == search_name):
           print (item for item in a).next()
      else:
           print 'No Name'

我不想看到'没有名字'的消息

3 个答案:

答案 0 :(得分:0)

实现它的更简洁方法是:

for dic in a:
    name = dic.get('name')  # will return None if dic has no `name` key
    if name and name == search_name:
        print dic
    else:
        print 'No Name'

但无论如何,如果不想看No Name,那么就不要打印它。

答案 1 :(得分:0)

当然你看到了。您迭代字典键(for key in i),当您尝试将i["age"]search_name匹配时,它会显示No Name

答案 2 :(得分:0)

for dict in a:
    if search_name in dict.values():
        print dict
    else:
        print "No name"