CSC111 Lab 12 2010
This lab deals with dictionaries. |
Dictionaries
Dictionaries are data structures in Python that have the following properties:
- they key track of pairs of elements. The first one is the key, the second the value
- all the keys are unique
- dictionaries allow fast searching, insertion and retrieval of information.
Playing with Dictionaries
- Use Python in interactive mode and enter the different Python statements shown below.
- Observe the output, and make sense of how dictionaries work in Python
>>>
>>> # create an empty dictionary
>>> D = {}
>>> D
>>> # create a dictionary with a few key:value pairs
>>> D = { "apple":30, "pear":10, "banana":5 }
>>> D
>>> # inspect some of the contents
>>> D[ 'pear' ]
>>> D[ 'apple' ]
>>> # we are getting 25 more bananas...
>>> D[ 'banana' ] = D[ 'banana' ] + 25
>>> D[ 'banana' ]
>>> D
>>> # we're getting a new shipment of pineapples... 100 of them
...
>>> D[ 'pineapple' ] = 100
>>> D
>>> # we want the name of the fruits (keys) we carry...
>>> D.keys()
>>> for fruit in D.keys():
... print fruit
...
>>>
>>> # we want to print the full inventory
...
>>> for key in D.keys():
... print D[ key ], "units of", key
...
- Now that you better understand how dictionaries work, try to figure out how to answer the following question in Python (use the interactive mode:
- Question 1
- How many bananas do we have?
- Question 2
- We sell half of the bananas. Remove half of the bananas from your inventory.
- Question 3
- Print the fruits for which we have more than 50 units.