andrew andrew - 21 days ago 8
Python Question

Print key-value pairs of a dictionary in python

How I can print key-value pairs in this situation:

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'


I don't want to see 'No name' message

Answer

A cleaner way to achieve it would be:

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'

But anyway, if don't wan't to see No Name then simply don't print it.