Reputation: 23
I have a list of dictionaries and there is also an element of comments, how can I print the numbers with comment while printing this list like this ,
here is my code in python
entries = [{'First Name': 'Sher', 'Last Name': 'Khan', 'Age': '22', 'Telephone': '2989484'},
{'First Name': 'Ali', 'Last Name': 'Khan', 'Age': '22', 'Telephone': '398439'},
{'First Name': 'Talha', 'Last Name': 'Khan', 'Age': '22', 'Telephone': '3343434', 'comments': []}]
search = input("type your search: ")
if search in [person['Last Name'] for person in entries]:
for person in entries:
if person["Last Name"] == search:
print("Here are the records found for your search")
for e in person:
if e == "comments":
for comment in person["comments"]:
print(comment)
else:
print(e, ":", person[e])
else:
print("There is no record found as you search Keyword")
Upvotes: 0
Views: 58
Reputation: 5531
You can use enumerate
:
entries = [{'First Name': 'Sher', 'Last Name': 'Khan', 'Age': '22', 'Telephone': '2989484'},
{'First Name': 'Ali', 'Last Name': 'Khan', 'Age': '22', 'Telephone': '398439'},
{'First Name': 'Talha', 'Last Name': 'Khan', 'Age': '22', 'Telephone': '3343434', 'comments': ['Comment 1','Comment 2']}]
search = input("type your search: ")
if search in [person['Last Name'] for person in entries]:
for person in entries:
if person["Last Name"] == search:
print("Here are the records found for your search")
for e in person:
if e == "comments":
for index,comment in enumerate(person[e]):
print(f"{index+1}. {comment}")
else:
print(e, ":", person[e])
else:
print("There is no record found as you search Keyword")
Output:
type your search: >? Khan
Here are the records found for your search
First Name : Sher
Last Name : Khan
Age : 22
Telephone : 2989484
Here are the records found for your search
First Name : Ali
Last Name : Khan
Age : 22
Telephone : 398439
Here are the records found for your search
First Name : Talha
Last Name : Khan
Age : 22
Telephone : 3343434
1. Comment 1
2. Comment 2
Upvotes: 2