Go to: Na-Rae Han's home page  

Python 2.7 Tutorial

With Videos by mybringback.com

#14: Dictionaries

                          << Previous Tutorial           Next Tutorial >>
On this page: dict (dictionary), dictionary key and value, updating a dictionary with a new entry/value, .keys(), .values(), .items().

Get Started

Video Summary

  • Script initial version, 2nd version, and 3rd version. The shell outputs here.
  • A dictionary in Python is an unordered set of key: value pairs.
  • Unlike lists, dictionaries are inherently orderless. The key: value pairs appear to be in a certain order but it is irrelevant.
  • Each KEY must be unique, but the VALUES may be the same for two or more keys.
  • If you assign a value to a key then later in the same dictionary have the same key assigned to a new value, the previous value will be overwritten.
  • Instead of using a number to index the items (as you would in a list), you must use the specific key, e.g., bringBackDict['Trav'].

Learn More

  • Is there a way to add a new entry or change a value of a key? Yes there is -- it's done through an assignment statement:
     
    >>> simpsons = {'Homer':36, 'Marge':35, 'Bart':10}
    >>> simpsons['Lisa'] = 8              # Add a new entry
    >>> simpsons
    {'Homer': 36, 'Lisa': 8, 'Marge': 35, 'Bart': 10} 
    >>> simpsons['Marge'] = 36            # Update value for key 'Marge'
    >>> simpsons
    {'Homer': 36, 'Lisa': 8, 'Marge': 36, 'Bart': 10} 
    
  • There are three dictionary methods for extracting certain data. .keys() returns the keys in the dictionary as a list, and .values() returns the dictionary values as a list.
     
    >>> simpsons.keys()         # .keys() returns list of keys
    ['Homer', 'Lisa', 'Marge', 'Bart']
    >>> simpsons.values()       # .values() returns list of values
    [36, 8, 35, 10]
    
    On the other hand, .items() returns both keys and values, but as a list of (key, value) tuples:
     
    >>> simpsons.items()        # .items() returns a list of key, value tuples
    [('Homer', 36), ('Lisa', 8), ('Marge', 35), ('Bart', 10)]
    
  • Dictionaries are orderless, but often it's necessary to impose a certain order (e.g., alphabetical) when processing dictionary entries. You achieve this by sorting the keys. See Sorting for details.

Explore