Monday, June 14, 2010

Dictionaries — Groupings of Data Indexed by Name


A dictionary is similar to lists and tuples. It’s another type of container for a group of data. However,
whereas tuples and lists are indexed by their numeric order, dictionaries are indexed by names that you
choose. These names can be letters, numbers strings, or symbols — whatever suits you.

Making a Dictionary
Dictionaries are created using the curly braces. To start with, you can create the simplest dictionary,
which is an empty dictionary, and populate it using names and values that you specify one per line:
    >>>  menus_specials = {}
    >>>  menus_specials[“breakfast”] = “canadian ham”
    >>>  menus_specials[“lunch”] = “tuna surprise”
    >>>  menus_specials[“dinner”] = “Cheeseburger Deluxe”

for example :-
>>> menu_specials = {“breakfast” : “sausage and eggs”,
...     “lunch” : “split pea soup and garlic bread”,
...     “dinner”: “2 hot dogs and onion rings”}

>>> print “%s” % menu_specials[“breakfast”]
sausage and eggs
>>> print “%s” % menu_specials[“lunch”]
split pea soup and garlic bread
>>> print “%s” % menu_specials[“dinner”]
2 hot dogs and onion rings

Getting the Keys from a Dictionary
Dictionaries can tell you what all of their keys are, or what all of their values are, if you know how to ask
them. The keys method will ask the dictionary to return all of its keys to you as a list so that you can
examine them for the key (or keys) you are looking for, and the values method will return all of the val-
ues as a list.
    >>> menu_specials.keys()
    [‘lunch’, ‘breakfast’, ‘dinner’]
    >>> menu_specials.values()
    [‘split pea soup and garlic bread’, ‘sausage and eggs’, ‘2 hot dogs and onion
    rings’]

One other thing to note about a dictionary is that you can ask the list whether a particular key already
exists. You can use a special built-in method called __contains__, which will return True or False.
When you invoke a method like __contains__, you are asking a question of it, and it will answer with
its version of yes, which is True or no, which is False.
>>> menu_specials.__contains__(“midnight specials”)
False
>>> menu_specials.__contains__(“Lunch”)
False
>>> menu_specials.__contains__(“lunch”)
True

No comments:

Post a Comment