Using dictionaries

Data Types in Python

Jason Myers

Instructor

Creating and looping through dictionaries

  • Hold data in key/value pairs
  • Nestable (use a dictionary as the value of a key within a dictionary)
  • Iterable
  • Created by dict() or {}
art_galleries = {}

for name, zip_code in galleries:
    art_galleries[name] = zip_code
Data Types in Python

Printing in the loop

for name in sorted(art_galleries)[-5:]:
    print(name)
Zwirner David Gallery
Zwirner & Wirth
Zito Studio Gallery
Zetterquist Galleries
Zarre Andre Gallery
Data Types in Python

Safely finding by key

art_galleries['Louvre']
|--------------------------------------------------------------------
KeyError                            Traceback (most recent call last)
<ipython-input-1-4f51c265f287> in <module>()
--> 1 art_galleries['Louvre']

KeyError: 'Louvre'
  • Getting a value from a dictionary is done using the key as an index
  • If you ask for a key that does not exist that will stop your program from running in a KeyError
Data Types in Python

Safely finding by key (cont.)

  • .get() method allows you to safely access a key without error or exception handling
  • If a key is not in the dictionary, .get() returns None by default or you can supply a value to return
art_galleries.get('Louvre', 'Not Found')
'Not Found'
art_galleries.get('Zarre Andre Gallery')
'10011'
Data Types in Python

Let's practice!

Data Types in Python

Preparing Video For Download...