Title: Iterating Over Dictionary Keys Slug: iterating_over_dictionary_keys_python
Summary: Iterating Over Python Dictionary Keys
Date: 2016-09-06 12:00
Category: Python
Tags: Basics
Authors: Chris Albon

Create A Dictionary


In [1]:
Officers = {'Michael Mulligan': 'Red Army',
            'Steven Johnson': 'Blue Army',
            'Jessica Billars': 'Green Army',
            'Sodoni Dogla': 'Purple Army',
            'Chris Jefferson': 'Orange Army'}

In [2]:
Officers


Out[2]:
{'Chris Jefferson': 'Orange Army',
 'Jessica Billars': 'Green Army',
 'Michael Mulligan': 'Red Army',
 'Sodoni Dogla': 'Purple Army',
 'Steven Johnson': 'Blue Army'}

Use Dictionary Comprehension


In [3]:
# Display all dictionary entries where the key doesn't start with 'Chris'
{keys : Officers[keys] for keys in Officers if not keys.startswith('Chris')}


Out[3]:
{'Jessica Billars': 'Green Army',
 'Michael Mulligan': 'Red Army',
 'Sodoni Dogla': 'Purple Army',
 'Steven Johnson': 'Blue Army'}

Notice that the entry for 'Chris Jefferson' is not returned.