I am trying to iterate through a list of dictionaries in Python, and for each dictionary present all the key:value pairs. I want to print each dictionary on it's own line, as well as count the line entries.
list_dict = [{'name':'d1', 'color':'red'},{'name':'d2', 'color':'green'},{'name':'d3','color':'blue}]
when I use
for i in list_dict:
print(i)
I get a very 'ugly' printout (including brackets and quotation marks) However, when I try to use a nested loop:
for i in list_dict:
for key, val in i.items():
print(key, ':', val, end=" ")
the code will print ALL THE DATA FROM ALL DICTIONARIES in the same line. I am looking for a way to print each dictionaries keys and values on a new line. Additionally, I would like to also number the lines (1. key:value, key:value) etc. Since i becomes a dictionary and not an integer, printing i does not work. I was sort of able to go around this by wrapping the whole thing in ANOTHER for loop
for i in range(len(list_dict)):
(some code)
but I'm wondering if there is a better way to do all of this? Thanks!
CodePudding user response:
You could try something like this:
j = 1
for i in list_dict:
print(j, end= " ")
for key, val in i.items():
print(key, ':', val, end=" ")
print('\n')
j = 1
This is far from the most elegant and/or optimized solution, but it works for the case stated.
CodePudding user response:
You can use
for print data in new line you can do
for i in list_dict:
for key, val in i.items():
print(key, ':', val, end="\n")
also remove end=" "
for i in list_dict:
for key, val in i.items():
print(key, ':', val)
For print data of dictionary like 1:key:value
itr=1
for i in list_dict:
for key, val in i.items():
print(itr,':',key, ':', val, end="\n")
itr=itr 1
Complete Code
list_dict = [{'name':'d1', 'color':'red'},{'name':'d2', 'color':'green'},{'name':'d3','color':'blue'}]
itr=1
for i in list_dict:
for key, val in i.items():
print(itr,':',key, ':', val)
itr=itr 1

