Reputation: 631
I am trying to print the value of a specific key in a list of dicts:
eg:
list = [{'a' : 123, 'b': 'xyz', 'c': [1,2]}, {'a' : 456, 'b': 'cde', 'c': [3,4]}]
I was hoping to be able to print the following for each dict:
print ("a: ", a)
print ("b: ", b)
Upvotes: 1
Views: 180
Reputation: 859
lst = [{'a' : 123, 'b': 'xyz', 'c': [1,2]}, {'a' : 456, 'b': 'cde', 'c': [3,4]}]
output=['a','b']
for dct in lst:
for k in output:
print(k+': '+str(dct[k]))
Upvotes: 0
Reputation: 155333
If you're guaranteed those keys exist, a nice solution using operator.itemgetter
:
from operator import itemgetter
# Renamed your list; don't name variables list
for a, b in map(itemgetter('a', 'b'), mylist):
print("a:", a)
print("b:", b)
The above is just a slightly optimized version of the import free code, pushing the work of fetching values to the builtins instead of doing it over and over yourself.
for d in mylist: # Renamed your list; don't name variables list
print("a:", d['a'])
print("b:", d['b'])
Oh, and for completeness (Aaron Hall is right that it's nice to avoid redundant code), a tweak to itemgetter
usage to observe DRY rules:
keys = ('a', 'b')
for values in map(itemgetter(*keys), mylist):
for k, v in zip(keys, values):
print(k, v, sep=": ")
Upvotes: 1
Reputation: 394825
How about some nested loops, to avoid hard-coding it?
for dictionary in list: # rename list so you don't overshadow the builtin list
for key in ('a', 'b'):
print(key + ':', dictionary[key])
which should output:
a: 123
b: xyz
a: 456
b: cde
Upvotes: 0