CSC111 Lab 12 2010

From dftwiki3
Revision as of 11:01, 21 April 2010 by Thiebaut (talk | contribs) (Created page with '{| | __TOC__ | <bluebox> This lab deals with dictionaries. </bluebox> |} ==Dictionaries== Dictionaries are data structures in Python that have the following properties: * they …')
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

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:
  • How many bananas to we have?
  • We sell half of the bananas. Remove half of the bananas from your inventory.
  • Print the fruits for which we have more than 50 units.