I have a list of dictionaries from which I need to extract information, and then print it out in a special format.
dict_list = [ {'description' : 'item 1', 'amount' : int_amount1 }, {'description' : 'item 2', 'amount' : int_amount2 }, {'description' : 'item 3', 'amount' : int_amount3 ]
I need to access the values in these dictionaries and print them out in the following way:
'item 1' int_amount1 'item 2' int_amount2 'item 3' int_amount3
If possible I would also need to print each key value at 20 characters max. Thus far I have tried for loops and list comprehensions but the farthest I’ve gotten is just printing out all the values in a one by one list.
Any help would be appreciated.
Advertisement
Answer
You just need to iterate over the list
and do your printing for each item
dict_list = [ {'description': 'item 1', 'amount': 'int_amount1'}, {'description': 'item 2', 'amount': 'int_amount2'}, {'description': 'item 3', 'amount': 'int_amount3'} ] for item in dict_list: print(f"{item['description']:20s}{item['amount']:20s}")
Giving
item 1 int_amount1 item 2 int_amount2 item 3 int_amount3