v Iterating Over Dictionary Keys - Python

Iterating Over Dictionary Keys

Create A Dictionary

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

Use Dictionary Comprehension

# Display all dictionary entries where the key doesn't start with 'Chris'
{keys : Officers[keys] for keys in Officers if not keys.startswith('Chris')}
{'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.