Python dicts

#Dictionaries are a useful way to store information about a range of items that you can then interrogate in various ways

#Dictionaries allow you to create a list of items and their values - more like a database than a list
#Whereas lists are accessed by items' positions, dictionaries are accessed by item names

#Here's a line of code that creates a dictionary

myfridge = {'topshelf': 'ham', 'bottom_shelf': 'cheese', 'inner_door': 'milk'}

#The curly brackets tell us that this is a dict
#the colon assigns a value to each item
#the comma separates each item/value pairing

#these can then be 'called' as follows:

myfridge['inner_door']

#this will return whatever value is associated with 'inner_door'

#new values can be added as follows:

myfridge['middle_shelf'] = 'beer'

#values can also be deleted with the del keyword:

del myfridge['middle_shelf']

#functions can be inserted into a dictionary and will run when called - more detail in Learn Python the Hard Way.

Read the rest of this post »