I have a list of dictionaries from which I need to extract information, and then print it out in a special format.
JavaScript
x
11
11
1
dict_list = [
2
{'description' : 'item 1',
3
'amount' : int_amount1
4
},
5
{'description' : 'item 2',
6
'amount' : int_amount2
7
},
8
{'description' : 'item 3',
9
'amount' : int_amount3
10
]
11
I need to access the values in these dictionaries and print them out in the following way:
JavaScript
1
4
1
'item 1' int_amount1
2
'item 2' int_amount2
3
'item 3' int_amount3
4
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
JavaScript
1
9
1
dict_list = [
2
{'description': 'item 1', 'amount': 'int_amount1'},
3
{'description': 'item 2', 'amount': 'int_amount2'},
4
{'description': 'item 3', 'amount': 'int_amount3'}
5
]
6
7
for item in dict_list:
8
print(f"{item['description']:20s}{item['amount']:20s}")
9
Giving
JavaScript
1
4
1
item 1 int_amount1
2
item 2 int_amount2
3
item 3 int_amount3
4