Do you think the following is a good definition for
Reeborg?
robot: a machine that can automatically do tasks normally
controlled by humans and mostly is used to perform repetitive
tasks.
Knowing how to look up the definition of a word in a dictionary is very useful when you want to write a story. Python has its own kind of dictionaries that are very useful when you are writing programs.
Our list of ingredients was very useful... However, without looking, do you remember how many eggs we needed? Could you find out without printing the whole list if you didn't remember? Unless you remembered in which order the ingredients came, you might find it difficult. However, if we had used a different Python object, namely a dict, it would have been very easy. Here's an example:
>>> ingredients2 = { 'eggs' : 4, # notice the curly bracket after the = sign? ... 'sugar': '100 g', ... 'cocoa powder': '30 ml', ... 'semi-sweet chocolate': '250 g'} # curly bracket here too. >>> print ingredients2 {'eggs': 4, 'semi-sweet chocolate': '250 g', 'cocoa powder': '30 ml', 'sugar': '100 g'}
Each entry in a dict is of the form "key : value", with a comma separating each entry from the next. Notice how, when we print ingredients2, the order in which the items appear is different from the order in which we put them in.
Now, if we want the number of eggs, we simply do:
>>> print ingredients2['eggs']
4
If we want to find out all the values contained in ingredients2, we can do the following:
>>> for key in ingredients2: ... print ingredients2[key] ... 4 250 g 30 ml 100 g
We can also do the following:
>>> for key in ingredients2: ... print str(key) + ":" + str(ingredients2[key]) eggs:4 semi-sweet chocolate:250 g cocoa powder:30 ml sugar:100 g
We have used the built-in function str() which converts any object into a string, so that we could do the proper string concatenation when we printed.
Oh-oh... it appears that I forgot the topping again! Let's add it:
>>> ingredients2["whipped cream"] = "Lots!"
Try it!
While we can put any object as a value in a dict, only immutable objects can be used as keys. We will see a bit later what that means; for now, it means that, of all the objects we have seen, only strings and numbers can be used for keys in a dict. You can not use lists and you can not use other dicts. Try various combinations of these objects as either key or value in a dict, and see what Python tells you!
Can you guess how to remove an entry from a dict? If so, try it. If not, it probably means that you haven't paid much attention in last lesson. Go back and read it, especially the part where we explained how to remove an item from a list.