Jand
Jand

Reputation: 2727

How to loop over a list of dictionaries?

I have a list like:

mylist = [{2: 1451989654}, {3: 1435222955}, {4: 1346726067}, {53: 1451887667}, {723: 1445763454}]

I'd like to do something like

for key, val in mylist:
   print key 
   print val

How best can I achieve this?

Upvotes: 0

Views: 52

Answers (2)

MSeifert
MSeifert

Reputation: 152647

Since you don't have duplicate keys in your dictionaries why do you save it inside a list?

You can just save everything in one dictionary (or convert it later) so it's much easier to access the data (including printing):

mylist = [{2: 1451989654}, {3: 1435222955}, {4: 1346726067}, {53: 1451887667}, {723: 1445763454}]
mydict = {k:d[k] for d in mylist for k in d} # Convert the list to one dictionary
for k in mydict:
    print k, mydict[k]

and this prints:

2 1451989654
3 1435222955
4 1346726067
53 1451887667
723 1445763454

notice however that if you want your data ordered you might need to default to OrderedDict and replace the conversion with:

mydict = OrderedDict([(k, d[k]) for d in mylist for k in d])

Upvotes: 1

AChampion
AChampion

Reputation: 30258

mylist is a list so you would need to loop through the list first:

for dct in mylist:
    for key, val in dct.items():
        print key
        print val

Note: you need dict.items() (or .iteritems()) to get both key and value

Upvotes: 5

Related Questions