加载中...
You are here:About>Computing & Technology>Python
About.comPython

Beginning Python: Data Types

From Al Lukaszewski,
Your Guide to Python.
FREE Newsletter. Sign Up Now!

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

  1. Introduction
  2. Integers
  3. Strings - Part 1
  4. Strings - Part 2
  5. Strings - Part 3
  6. Accessing Variables
  7. Working With Variables
  8. Lists
  9. Tuples
  10. Dictionaries

<< Previous | Next

 All Topics | Email Article | Print this Page | |
Advertising Info | News & Events | Work at About | SiteMap | Reprints | HelpOur Story | Be a Guide
User Agreement | Ethics Policy | Patent Info. | Privacy Policy©2008 About, Inc., A part of The New York Times Company. All rights reserved.