1. Home
  2. Computing & Technology
  3. Python

Beginning Python: Data Types

From Al Lukaszewski, for About.com

10 of 10

Dictionaries

Defining a Dictionary

Dictionary is the Python term for an associative array. An array is, like a list, a series of values in two dimensions. An associative array gives one a way of accessing the values by a key, a term associated with the value instead of an item's index number.

Initializing a dictionary, one offsets the keys and values in curly braces. Each key-value pair is separated from the others by a comma. For each pair, the key and value are separated by a colon. The key of each member is offset in quotes. A sample dictionary is as follows:

my_dictionary = {                  "author" : "Andrew Melville",
                 "title" : "Moby Dick",
                 "year" : "1851",
                 "copies" : 5000000
}

Accessing a Dictionary

One accesses a dictionary member by its key:

>>> a = my_dictionary["author"]
>>> print a
Andrew Melville

To insert or modify a member, one simply assigns the value:

>>> my_dictionary["publisher"] = 'Harper and Brothers'
>>> my_dictionary["author"] = 'Herman Melville'
>>> print my_dictionary
{'publisher': 'Harper and Brothers', 'title': 'Moby Dick', 'year': '1851', 'copies': 5000000, 'author': 'Herman Melville'}

Other tutorials in this series: 1 | 2 | 3 | 4 | 5 | 6

Explore Python
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. Python

©2009 About.com, a part of The New York Times Company.

All rights reserved.