Read list of a dictionaries
My students wanted a quick example of how to read a list of a dictionaries in Python. So, here it is:
#!/usr/bin/python # Declare list of dictionaries. cakes = [{'cake':"vanilla",'frosting':"chocolate"} ,{'cake':"chocolate",'frosting':"vanilla"}] # 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.