Go to: Na-Rae Han's home page  

Python 3 Notes

        [ HOME | LING 1330/2330 ]

Tutorial 11: 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().

Video Tutorial


Python 3 Changes

print(x,y) instead of print x, y

Video Summary

  • 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 (sort of), and .values() returns the dictionary values as a list (sort of). Why "sort of"? Because the returned objects are not a list per se -- they are their own list-like types, called dict_keys and dict_values.
     
    >>> simpsons.keys()         # .keys() returns list-like object consisting of keys
    dict_keys(['Homer', 'Lisa', 'Marge', 'Bart'])
    >>> simpsons.values()       # .values() returns list-like object consisting of values
    dict_values([36, 8, 35, 10])
    
    On the other hand, .items() returns both keys and values, but as a quasi-list of (key, value) tuples:
     
    >>> simpsons.items()        # .items() returns a quasi-list of key, value tuples
    dict_items([('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.

Practice

Add Maggie and Grandpa Abe Simpson to the simpsons dictionary. Their respective ages: 1 and 65.

Explore