Close

Essential Dictionary Code for a Python Interview

Essential Dictionary Code for a Python Interview

This is a cheat sheet for dictionaries in Python. It provides examples for all of the common operations with the standard map type in Python. It covers all the items listed in Essential Interview Code for Maps and Dictionaries.

If you are doing a coding interview in Python, it is recommended to know all of these items, or to keep this list nearby.

It's also a handy list at work, for when some syntax has slipped your mind. Dictionary, and map, syntax changes slightly between languages, thus sometimes it's nice to have a quick reference available.

Basic

# Create a map
costs = {
	'apple': 3.5,
	'banana': 4.2,
	'avacado': 9.2,
}

# Add an element with a key and a value
costs['orange'] = 4.1
costs.update({
	'tomato': 3.2,
	'lime': 6.9,
})


# Check if an element exists by key
if 'tomato' in costs:
	print( "Yummy Red" )
	
# Get an element by key
print( costs['banana'] )

# Get the length of the map
print( len( costs ) )

# Check and get
value = costs.get( 'avacado' )
if value != None:
	print( value )

Searching and Removal

# Replace an item by key
costs['apple'] = 4.5

# Find an item by value
key = list(costs.keys())[list(costs.values()).index(9.2)]

# Get by key or default value
print( costs.get( 'lemon', 4 ) )

# Delete an element by key
del costs['banana']
costs.pop( 'apple' )

# Clear the map
costs.clear()

Iteration

# Iterate all key and value pairs in the map
for key, value in costs.items():
	print( f'{key} = {value}' )

# Iterate the keys of the map
for key in costs.keys():
	print( key )
	
# Iterate the values of the map
for value in costs.values():
	print( value )

# Iterate in sorted order	
# Use the standard `sorted` function on the pairs, keys, or values
for key, value in [(key, costs[key]) for key in sorted(costs.keys())]:
	print( f'{key} = {value}' )

Full-map operations

We don’t always want to work with the full map, or may wish to isolate certain items.

# Produce a shallow clone of a map
shallow_copy = costs.copy()

# Map the values of a map to a new map
in_cents = {key: math.floor(value * 100) for key, value in costs.items()}

# Merge the contents of two maps (new values take precedence)
costs.update({
	'coconut': 5.2,
	'avacado': 8.7,
})

# Filter items by key
only_o = {key: value for key, value in costs.items() if key.endswith('o')}

# Filter items by value
cheap = {key: value for key, value in costs.items() if value < 5}

Mutli-maps

Python does not have a stand multi-map type, but the defaultdict with a list can be used similarly.

# Create a multi-map
from collections import defaultdict
books = defaultdict(list)

# Add an item by key
books['jose'].append( 'Red Duck' )
books['jose'].append( 'Blue Duck' )
books['rosie'].append( 'Eight Swans' )
books['greg'].append( 'Greggy' )

# Iterate the items matching a key
for book in books['jose']:
	print( book )

for book in books['nobody']:
	print( book )

# Remove an item matching a key
books['jose'].pop()

# Replace all items matching a key
books['rosie'] = [ 'Turtle Turtle', 'Alien Invasion' ]

# Clear all items with a key
books.pop('greg')
del books['jose']

Edaqa Mortoray

An avid writer and expert programmer. He’s been on both sides of the interview table countless times and enjoys sharing his experiences. https://edaqa.com/