在这种情况下如何打印键值对:
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'
我不想看到'没有名字'的消息
答案 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"