MacLochlainns Weblog

Michael McLaughlin's Technical Blog

Site Admin

Read list of a dictionaries

without comments

My students wanted a quick example of how to read a list of a dictionaries in Python. So, here it is:

# Declare list of dictionaries.
cakes = [{'cake':"vanilla",'frosting':"chocolate"}
# Read the list of dictionaries.
for lkey, lvalue in enumerate(cakes):
  print lvalue['cake'] + " with " + lvalue['frosting'] + " frosting."

Naturally, a list can contain many things and you should ensure each value you read is a dictionary before trying to read it as a dictionary. At least, I’d suggest you check.

Hope this answers the how.

Written by maclochlainn

June 1st, 2017 at 9:09 pm