17. Dictionaries#
Dictionaries are unordered collections of key-value pairs. Generally, we use strings for keys, but keys can be any immutable type. The primary immutable types we have seen so far are strings, ints, and floats. Python does have an immutable version of a list type called tuple. Values can be of any type - including other dictionaries and lists.
Keys must be unique. If we attempt to store another key-value pair where the key already exists, the new value replaces the previous value in the dictionary.
Programmers use dictionaries (i.e., associative arrays) quite frequently. For example, translating one value to another value, e.g., a stock symbol to a stock name or a word in English to its counterpart in another language. We could also have a dictionary where the key is a university course name, and the values are a list of students within that course. Another dictionary could map HTTP response status codes to their descriptions: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status. Retailers often use SKUs to track products and inventory. The SKU could be the key, while the value may be another dictionary keeping track of a series of properties the retailer needs for each product: name, purchase_price, selling_price, inventory_count, …
As with lists, dictionaries are another example of data structures. A dictionary organize the data as unordered collection of key-value pairs. Accessing the dictionary with the key allows us to quickly retrieve a particular value. The primary relationship in the dictionary is the key to value mapping. Keys have an unordered relationship to other keys. However, keys must be unique among themselves - a unique relationship. Throughout this notebook, you will see the various operations that exist for dictionaries.
As with other collections, we have different ways of creating dictionaries - literals with {}
and the dict()
function.
17.1. Creating: Literals#
With literals, we can either create an empty dictionary or use a sequence of key-value pairs to populate a dictionary.
1empty_dict = {}
2empty_dict
{}
1stocks = { "AXP" : "American Express",
2 "AMGN" : "Amgen",
3 "AAPL" : "Apple",
4 "BA" : "Boeing"}
5print(stocks)
{'AXP': 'American Express', 'AMGN': 'Amgen', 'AAPL': 'Apple', 'BA': 'Boeing'}
As a side note, we intentionally used extra whitespace while creating the dictionary to make the code easier to read. We can format this code multiple ways:
stocks = {'AXP': 'American Express', 'AMGN': 'Amgen', 'AAPL': 'Apple', 'BA': 'Boeing'}
stocks = { "AXP" : "American Express", "AMGN" : "Amgen",
"AAPL" : "Apple",
"BA" : "Boeing"}
17.2. Creating: dict()#
We can pass named arguments and values to the built-in dict()
function.
1more_stocks = dict(CAT='Caterpillar', CVX='Chevron', CSCO='Cisco', KO='Coca-Cola')
2more_stocks
{'CAT': 'Caterpillar', 'CVX': 'Chevron', 'CSCO': 'Cisco', 'KO': 'Coca-Cola'}
With this named argument method, argument names must follow the naming rules for variables: no spaces, no reserved words, and the name must start with a letter or underscore.
Creating dictionaries from two-value sequences:
1from_list_of_list = dict([ ['DIS', 'Walt Disney Co'], ['DOW', 'Dow'], ['GS', 'Goldman Sacs'], ['HD', 'Home Depot'] ])
2from_list_of_list
{'DIS': 'Walt Disney Co',
'DOW': 'Dow',
'GS': 'Goldman Sacs',
'HD': 'Home Depot'}
17.3. Combining Dictionaries#
Python has two different ways to combine dictionaries.
First, we can use {**a, **b}
operator.
1combined = { **more_stocks, **from_list_of_list}
2combined
{'CAT': 'Caterpillar',
'CVX': 'Chevron',
'CSCO': 'Cisco',
'KO': 'Coca-Cola',
'DIS': 'Walt Disney Co',
'DOW': 'Dow',
'GS': 'Goldman Sacs',
'HD': 'Home Depot'}
Or, we can use the .update()
method. If both dictionaries contain the same key, the value from the dictionary in the argument takes precedence.
1more_stocks.update(from_list_of_list)
2more_stocks
{'CAT': 'Caterpillar',
'CVX': 'Chevron',
'CSCO': 'Cisco',
'KO': 'Coca-Cola',
'DIS': 'Walt Disney Co',
'DOW': 'Dow',
'GS': 'Goldman Sacs',
'HD': 'Home Depot'}
1stocks.update(combined)
2stocks.update(more_stocks)
3stocks
{'AXP': 'American Express',
'AMGN': 'Amgen',
'AAPL': 'Apple',
'BA': 'Boeing',
'CAT': 'Caterpillar',
'CVX': 'Chevron',
'CSCO': 'Cisco',
'KO': 'Coca-Cola',
'DIS': 'Walt Disney Co',
'DOW': 'Dow',
'GS': 'Goldman Sacs',
'HD': 'Home Depot'}
17.4. Number of Entries / Length#
Use len() to
get a dictionary’s size (number of entries).
1len(stocks)
12
17.5. Adding, Changing, and Deleting Keys#
We can add and change keys by using the []
operator.
1stocks['UNH'] = 'UnitedHealth Group Inc'
2stocks['WBA'] = 'Walgreens Boot Alliance, Inc'
3stocks['WMT'] = 'Wally World'
4len(stocks)
15
We now have half of the thirty stocks of the Dow Jones Industrial Average, but we should correct Walmartʼs name.
1print(stocks['WMT'])
2stocks['WMT'] = 'Walmart Inc'
3print(stocks['WMT'])
Wally World
Walmart Inc
1stocks['TSLA'] = 'Tesla, Inc'
2stocks['TWTR'] = 'Twitter Inc'
Whoa, how did those last two appear? So what is Elon Musk doing now?
We can delete an entry in a dictionary with del
.
1del stocks['TWTR']
We can also get an item’s value and remove that entry simultaneously with pop()
.
1name = stocks.pop('TSLA')
2print(name)
3print(len(stocks))
Tesla, Inc
15
To reiterate, each key in a dictionary must be unique. If a routine tries to put a key-value pair into the dictionary and the key already exists, then the existing key’s value is replaced with the new value.
17.6. Getting an item by key#
We have already seen how to access an item by [key]
, but we can also get the value with get()
.
1print(stocks['WBA'])
2print(stocks.get('UNH'))
Walgreens Boot Alliance, Inc
UnitedHealth Group Inc
With get()
, we can specify a default value if the key doesn’t exist in the dictionary
1stocks.get('BAC','Unknown stock symbol')
'Unknown stock symbol'
The optional / default value comes in handy if we count items - such as the number of times various words appear in a document. In this case, the key is the word, and the value is the occurrence count. As we update the count, if we have not yet seen a particular word, we use a default value of 0
.
1word_counts = {}
2word = 'test'
3word_counts[word] = word_counts.get(word,0) + 1
4print(word_counts)
{'test': 1}
17.7. Getting all Keys#
Use the keys()
method to get an iterable view of all the keys in a dictionary. Before Python 3, this returned a list, but now it returns a type of dict_keys
. We can convert that view to a list with the built-in function list()
. The advantage of the dict_keys()
approach is that it does not necessarily create a list (which takes time and memory) with sizable dictionaries.
1symbols = stocks.keys()
2print(type(symbols))
3print(symbols)
4symbol_list = list(symbols)
5print(symbol_list)
<class 'dict_keys'>
dict_keys(['AXP', 'AMGN', 'AAPL', 'BA', 'CAT', 'CVX', 'CSCO', 'KO', 'DIS', 'DOW', 'GS', 'HD', 'UNH', 'WBA', 'WMT'])
['AXP', 'AMGN', 'AAPL', 'BA', 'CAT', 'CVX', 'CSCO', 'KO', 'DIS', 'DOW', 'GS', 'HD', 'UNH', 'WBA', 'WMT']
17.8. Getting all Values#
Similarly, use values()
to get an iterable view of all the values in a dictionary.
1names = stocks.values()
2print(type(names))
3print(names)
4name_list = list(names)
5print(name_list)
<class 'dict_values'>
dict_values(['American Express', 'Amgen', 'Apple', 'Boeing', 'Caterpillar', 'Chevron', 'Cisco', 'Coca-Cola', 'Walt Disney Co', 'Dow', 'Goldman Sacs', 'Home Depot', 'UnitedHealth Group Inc', 'Walgreens Boot Alliance, Inc', 'Walmart Inc'])
['American Express', 'Amgen', 'Apple', 'Boeing', 'Caterpillar', 'Chevron', 'Cisco', 'Coca-Cola', 'Walt Disney Co', 'Dow', 'Goldman Sacs', 'Home Depot', 'UnitedHealth Group Inc', 'Walgreens Boot Alliance, Inc', 'Walmart Inc']
17.9. Getting all Key-Value Pairs#
To get both the keys and values together as an iterable view, use items()
. As with keys()
and values()
, this now returns a type of dict_items
. Each item is a tuple consisting of a key and a value.
1stocks.items()
dict_items([('AXP', 'American Express'), ('AMGN', 'Amgen'), ('AAPL', 'Apple'), ('BA', 'Boeing'), ('CAT', 'Caterpillar'), ('CVX', 'Chevron'), ('CSCO', 'Cisco'), ('KO', 'Coca-Cola'), ('DIS', 'Walt Disney Co'), ('DOW', 'Dow'), ('GS', 'Goldman Sacs'), ('HD', 'Home Depot'), ('UNH', 'UnitedHealth Group Inc'), ('WBA', 'Walgreens Boot Alliance, Inc'), ('WMT', 'Walmart Inc')])
17.10. Iterating#
Using the keys()
, values()
, or items()
method, we can iterate over the keys, values, or key-value pairs of a dictionary.
1some_stocks = {'AXP': 'American Express', 'AMGN': 'Amgen', 'AAPL': 'Apple'}
2for symbol in some_stocks.keys():
3 print(symbol,end=':')
4print()
5# notice that we have a fencepost loop issue - code was to demonstrate iterating,
6# we could have called join() from a separator string
7":".join(some_stocks.keys())
AXP:AMGN:AAPL:
'AXP:AMGN:AAPL'
1for symbol in some_stocks.values():
2 print(symbol,end=':')
3print()
American Express:Amgen:Apple:
1for item in some_stocks.items():
2 print("Ticker: {:>4s}, Name: {}".format(item[0], item[1]))
Ticker: AXP, Name: American Express
Ticker: AMGN, Name: Amgen
Ticker: AAPL, Name: Apple
1for symbol, name in some_stocks.items():
2 print("{}: {}".format(symbol,name))
AXP: American Express
AMGN: Amgen
AAPL: Apple
17.11. Deleting all entries#
To delete (remove) all entries from the dictionary, use clear()
1some_stocks = {'AXP': 'American Express', 'AMGN': 'Amgen', 'AAPL': 'Apple'}
2print(len(some_stocks))
3some_stocks.clear()
4print(len(some_stocks))
5print(some_stocks)
3
0
{}
You can also assign an empty dictionary to the variable. However, if you have two variables that refer to the same table, the other variable still has a reference to the original dictionary. Visualize on PythonTutor
1some_stocks = {'AXP': 'American Express', 'AMGN': 'Amgen', 'AAPL': 'Apple'}
2stocks_dict = some_stocks
3print (some_stocks)
4
5some_stocks = {}
6print(some_stocks)
7print(stocks_dict)
{'AXP': 'American Express', 'AMGN': 'Amgen', 'AAPL': 'Apple'}
{}
{'AXP': 'American Express', 'AMGN': 'Amgen', 'AAPL': 'Apple'}
17.12. Checking if a key exists#
You can check if a key exists by using the in
operator. This evaluates to True
or False
.
1'IBM' in stocks_dict
False
17.13. Assignment#
We can use =
to have multiple variables refer to the same dictionary, as demonstrated a few cells back. Realize that any operation on one of those variables affects them all as they refer to the same underlying dictionary object.
Rename stocks to a more descriptive name.
1dow_stocks = stocks
However, note that dow_stocks
and stocks
still refer to the same object(dictionary):
1print(id(stocks))
2print(id(dow_stocks))
4356094080
4356094080
1s1 = {'AXP': 'American Express', 'AMGN': 'Amgen', 'AAPL': 'Apple'}
2s2 = s1
3s2['IBM'] = "International Business Machines"
4print(s1)
5s1.clear()
6print(s2)
{'AXP': 'American Express', 'AMGN': 'Amgen', 'AAPL': 'Apple', 'IBM': 'International Business Machines'}
{}
17.14. Copying#
To copy a dictionary to a new object, we can use the copy()
method. Copy creates a shallow copy that copies reference values, but not necessarily the objects to which those references point. For the simple dictionaries seen so far, we will not have any issues with mutability as strings are immutable. However, if you store mutable objects as values, you may have problems with unintended side-effect.
1s1 = {'AXP': 'American Express', 'AMGN': 'Amgen', 'AAPL': 'Apple'}
2s2 = s1.copy()
3s2['IBM'] = "International Business Machines"
4print(s1)
5print(s2)
6s1.clear()
7print(s1)
8print(s2)
{'AXP': 'American Express', 'AMGN': 'Amgen', 'AAPL': 'Apple'}
{'AXP': 'American Express', 'AMGN': 'Amgen', 'AAPL': 'Apple', 'IBM': 'International Business Machines'}
{}
{'AXP': 'American Express', 'AMGN': 'Amgen', 'AAPL': 'Apple', 'IBM': 'International Business Machines'}
You may need to use a deep copy if you store mutable objects (e.g., a list or another dictionary).
1import copy
2s1 = {'A': {'AX': 'American Express', 'AMGN': 'Amgen', 'AAPL': 'Apple'}}
3s2 = copy.deepcopy(s1)
4s2['A']['AA']='Alcoa Corp'
5print(s1)
6print(s2)
{'A': {'AX': 'American Express', 'AMGN': 'Amgen', 'AAPL': 'Apple'}}
{'A': {'AX': 'American Express', 'AMGN': 'Amgen', 'AAPL': 'Apple', 'AA': 'Alcoa Corp'}}
In the above example, we have a dictionary of dictionaries.
So s2['A']
refers to a dictionary(stocks that begin with the letter ‘A’), then s2['A']['AA']
refers to an entry in that “sub” dictionary. As that entry does not exist, it is created and assigned the value of ‘Alcoa Corp’.
In the following cell, print the dictionary for the stock symbols beginning with ‘A’ - i.e., just that dictionary that the key ‘A’ indexes. Then print out the value for ‘AX’.
1# Get the value that contains the dictionary in the dictionary s1. Print the value
2
3# From that dictionary, print out the value of the key 'AX'
17.15. Comparing#
Unlike some of the other built-in data types that hold multiple values (e.g., lists and tuples), we can only test dictionaries for equality with ==
and !=
.
1s1 = {'AXP': 'American Express', 'AMGN': 'Amgen', 'AAPL': 'Apple'}
2s2 = s1.copy()
3print (s1 == s2)
4s2['AA'] = 'Alcoa Corp'
5print (s1 != s2)
6print (s1 != s1)
True
True
False
17.16. Sorting#
To sort dictionaries, we first need to ask what are we sorting? We also need to ask what do we need to do with that sort?
17.16.1. Sort by Keys#
For example, if we need to sort by the dictionary’s keys and then print out information from the corresponding values, we can use the following pattern:
1stock_prices = {'PG': 141.96, 'AXP': 154.42, 'AAPL': 137.13,'CSCO':43.49, 'HD':289.24, 'AMZN': 2538.23}
2print(stock_prices)
3for key in sorted(stock_prices):
4 print("{}: Stock price: ${:,.2f}".format(key,stock_prices[key]))
{'PG': 141.96, 'AXP': 154.42, 'AAPL': 137.13, 'CSCO': 43.49, 'HD': 289.24, 'AMZN': 2538.23}
AAPL: Stock price: $137.13
AMZN: Stock price: $2,538.23
AXP: Stock price: $154.42
CSCO: Stock price: $43.49
HD: Stock price: $289.24
PG: Stock price: $141.96
17.16.2. Sort by Values#
To get a list of the sorted values, we need to get all of the values and then use the built-in function sorted()
as we did for lists.
1stock_prices = {'PG': 141.96, 'AXP': 154.42, 'AAPL': 137.13,'CSCO':43.49, 'HD':289.24, 'AMZN': 2538.23}
2print(stock_prices)
3print(sorted(stock_prices.values()))
4print(sorted(stock_prices.values(),reverse=True))
{'PG': 141.96, 'AXP': 154.42, 'AAPL': 137.13, 'CSCO': 43.49, 'HD': 289.24, 'AMZN': 2538.23}
[43.49, 137.13, 141.96, 154.42, 289.24, 2538.23]
[2538.23, 289.24, 154.42, 141.96, 137.13, 43.49]
To sort by values but produce a list of the corresponding keys, we need to pass a function as the “key” argument. (Later notebooks will discuss passing functions in more detail). The value returned by this function will be used in the sort comparisons.
1sorted(stock_prices,key=stock_prices.get)
['CSCO', 'AAPL', 'PG', 'AXP', 'HD', 'AMZN']
To understand the previous command and what occurred, try running just sorted(stock_prices)
.
1# Sort the dictionary without any arguments
We can also produce a list of tuples, where each tuple is a key-value pair. As shown above, to get the key-value pairs, call items()
on the dictionary:
1print (stock_prices.items())
2items = stock_prices.items()
3
4print(sorted(items))
dict_items([('PG', 141.96), ('AXP', 154.42), ('AAPL', 137.13), ('CSCO', 43.49), ('HD', 289.24), ('AMZN', 2538.23)])
[('AAPL', 137.13), ('AMZN', 2538.23), ('AXP', 154.42), ('CSCO', 43.49), ('HD', 289.24), ('PG', 141.96)]
By default, sorted uses the first item in the sequence. Similar behavior to sorting a dictionary, it just uses the key.
To sort by the second entry in the tuple, we need to specify a function to the key argument
1def sortAtSecondPosition(x):
2 return x[1]
1sorted(stock_prices.items(), key=sortAtSecondPosition)
[('CSCO', 43.49),
('AAPL', 137.13),
('PG', 141.96),
('AXP', 154.42),
('HD', 289.24),
('AMZN', 2538.23)]
Python provides a capability to create small, anonymous functions. While these functions can take any number of arguments, they can consist of only a single expression.
lambda p1{, pX}: expression
The {, pX}
signifies the portion may repeat zero or more times. p1, p2, …, pX represent parameters.
1sorted(stock_prices.items(), key=lambda x: x[1])
[('CSCO', 43.49),
('AAPL', 137.13),
('PG', 141.96),
('AXP', 154.42),
('HD', 289.24),
('AMZN', 2538.23)]
Note: As of Python 3.7, the order of iterating over a dictionary’s keys is gauranteed to be the same as the insert order. From a practicality point, though, if you ever explicitly need to specify the order (e.g., sorted), you should do so in code. Yes, the code may run a bit slower, but you avoid obtuse errors introduced by relying upon the insert order.
1stock_prices = { 'AAPL': 137.13, 'AXP': 154.42, 'AMZN': 2538.23,'CSCO':43.49, 'HD':289.24, 'PG': 141.96}
2print(stock_prices)
3# Prefer this approach
4for key in sorted(stock_prices):
5 print("{}: Stock price: ${:,.2f}".format(key,stock_prices[key]))
6print("-------------------")
7# over this (even though the results appear the same)
8for key in stock_prices:
9 print("{}: Stock price: ${:,.2f}".format(key,stock_prices[key]))
{'AAPL': 137.13, 'AXP': 154.42, 'AMZN': 2538.23, 'CSCO': 43.49, 'HD': 289.24, 'PG': 141.96}
AAPL: Stock price: $137.13
AMZN: Stock price: $2,538.23
AXP: Stock price: $154.42
CSCO: Stock price: $43.49
HD: Stock price: $289.24
PG: Stock price: $141.96
-------------------
AAPL: Stock price: $137.13
AXP: Stock price: $154.42
AMZN: Stock price: $2,538.23
CSCO: Stock price: $43.49
HD: Stock price: $289.24
PG: Stock price: $141.96
17.16.3. Sort by Multiple Criteria#
To sort by two or more items, we need to create a lambda function that produces a list or tuples of values. Recall, that when doing comparisons of lists and tuples, the first element is evaluated, then the second, the third, etc. until all of the entries have been compared. So we will use that same behavior to sort by multiple critera. The following code sorts by price descending and then the company name ascending:
1stock_prices = { 'AXP': 154.00, 'BAC': 154.00, 'AAPL': 154.00, 'AMZN': 2538.23,'CSCO':43.49, 'HD':289.24, 'PG': 141.96}
2for ticker in sorted(stock_prices, key=lambda x: (-stock_prices[x], x)):
3 print("{:>5}: {:8.2f}".format(ticker, stock_prices[ticker]))
AMZN: 2538.23
HD: 289.24
AAPL: 154.00
AXP: 154.00
BAC: 154.00
PG: 141.96
CSCO: 43.49
Notice that rather using the paramater reverse=True
, we negated the price -stock_prices[x]
. This allows the stock price to be sorted in descending order while the company ticker symbols are sorted in ascending order. More complex sort criteia would involve writing a custom comparison function (comparator). The following description has been adapted from https://stackoverflow.com/questions/5213033/sort-a-list-of-lists-with-a-custom-compare-function#57003713:
When providing a custom comparator, it should generally return an integer/float value that follows the following pattern (as with most other programming languages and frameworks):
return a negative value (
< 0
) when the left item should be sorted before the right itemreturn a positive value (
> 0
) when the left item should be sorted after the right itemreturn
0
when both the left and the right item have the same weight and should be ordered “equally” without precedence
To make this call in Python (compare is the sort function):
from functools import cmp_to_key
sorted(mylist, key=cmp_to_key(compare))
As an example, to compare prices ascending, but stock tickers descending we will use a customer comparator. We will also sort the result of “items()” so that our comparator is passed tuples with the key and value entries.
1from functools import cmp_to_key
2
3def compare(left, right):
4 if left[1] == right[1]: # stock prices are the same
5 if left[0] < right[0]:
6 return 1
7 elif left[0] > right[0]:
8 return -1
9 else:
10 return 0
11 elif left[1] < right[1]:
12 return -1
13 else:
14 return 1
15
16stock_prices = { 'AXP': 154.00, 'BAC': 154.00, 'AAPL': 154.00, 'AMZN': 2538.23,'CSCO':43.49, 'HD':289.24, 'PG': 141.96}
17for item in sorted(stock_prices.items(), key=cmp_to_key(compare)):
18 print("{:>5}: {:8.2f}".format(item[0], item[1]))
19
CSCO: 43.49
PG: 141.96
BAC: 154.00
AXP: 154.00
AAPL: 154.00
HD: 289.24
AMZN: 2538.23
17.17. Nesting different data structures#
Most of the dictionaries in this notebook have been straightforward key-value pairs of strings. However, realize that we can create arbitrarily complex data structures by nesting additional data structures as entries.
Lists can contain other lists, but they can also include a dictionary as an entry.
Dictionaries can have lists as values as well as other dictionaries as those values. For example, to manage the organizational hierarchy for a company, we could have \(n\)-nested dictionary, where \(n\) is the number of levels in the company’s hierarchy. The keys in the nested dictionary are the direct reports of an individual.
17.18. Suggested LLM Prompts#
Explain what a dictionary is in Python, its basic structure, and how it differs from other data structures like lists and tuples. Discuss the key-value pair concept, the flexibility of using different data types as keys and values, and the importance of dictionaries in various programming scenarios.
Provide examples of creating dictionaries using different methods, such as literal notation and the dict() constructor. Demonstrate how to access and modify values in a dictionary using keys, and discuss the handling of key errors (KeyError).
Why must Python dictionary keys be immutable?
Explore common dictionary operations, including adding and removing key-value pairs, checking for the existence of keys, getting lists of keys and values, and iterating over dictionaries using items(), keys(), and values() methods.
Explain the concept of nested dictionaries, where the values of a dictionary can be other dictionaries. Provide examples of creating and accessing nested dictionaries, and discuss potential use cases, such as representing hierarchical data structures.
Dive into the various built-in methods available for dictionaries, such as update(), pop(), popitem(), clear(), copy(), and get(). Explain their functionalities and use cases, and demonstrate their implementation with code examples.
Discuss techniques for sorting dictionaries based on keys or values. Explain how to use the sorted() function with dictionaries, and provide examples of sorting dictionaries using lambda functions or custom sorting functions.
Address the issue of handling duplicate keys in dictionaries. Explain how Python handles duplicate keys, and discuss strategies for dealing with them, such as overwriting values or raising exceptions.
Discuss the performance considerations of dictionaries in Python. Explain how dictionaries are implemented under the hood (hash tables), and discuss the time complexities of various dictionary operations. Provide guidelines for optimizing dictionary usage in performance-critical applications.
17.19. Review Questions#
What is a dictionary in Python, and how is it different from other data structures like lists and tuples?
How do you create an empty dictionary in Python?
What are the two main components of a dictionary in Python? Explain with an example.
How do you access the value associated with a specific key in a dictionary?
What happens if you try to access a key that doesn’t exist in a dictionary?
How do you add a new key-value pair to an existing dictionary?
How do you remove a key-value pair from a dictionary?
How do you check if a specific key exists in a dictionary?
How do you get a list of all keys or all values in a dictionary?
What function returns the number of elements in a dictionary?
For a given key, how many entries may exist for that key in a Python dictionary? What happens if you try to add a duplicate key to a dictionary?
What are the requirements(limitations) for a dictionary key?
Are dictionary entries unique?
How do you iterate over key-value pairs in a dictionary?
How do you sort a dictionary by keys or values in Python?
How do you copy a dictionary in Python?
What is the get() method in Python dictionaries, and how is it different from indexing with square brackets?
Can you have a dictionary as a value in another dictionary? If so, how would you access the nested dictionary?
17.20. Exercises#
Create a dictionary that maps top-level domain names to their description. Include at least three entries.
Now add another entry into your dictionary.
now delete one of the first entries you created from your dictionary
Iterate through your dictionary, printing the domain name and the corresponding description.
Create a dictionary where the keys are the numbers 1 to 10, and the values are the square of the corresponding key.
Find the minimum and maximum values in a dictionary.
For a given list of keys, delete those entries from the dictionary.
How could we check if a given value exists in the dictionary? How expensive is this operation? How could you measure it?
Write a function that calculates the frequency of characters in a string.
Physical money comes in many different denominations. Write a function that, for a given amount, returns a dictionary containing the smallest number of bills and coins that add up to that number. Do not place any entries in the dictionary that are zero. The possible denominations are 100.00, 50.00, 20.00, 10.00, 5.00, 2.00, 1.00, 0.25, 0.10, 0.05, and 0.01.
Write a method to create a text-based horizontal histogram. You should have the following function signature:
def create_histogram(data, title, sort=False, max_table_width=70, max_label_width=10):
So the following -
data = { "apples": 58, "pears": 10, "grapes":35, "pineapple":70}
create_histogram(data,"Number of Fruits in Basket", max_table_width=80, max_label_width=7)
produces
Number of Fruits in Basket
apples │*********************************************************** 58
pears │********** 10
grapes │************************************ 35
pineapp │************************************************************************ 70
└───────────────────────────────────┰───────────────────────────────────┐
0 35 70
Then
create_histogram(data,"Number of Fruits in Basket", sort=True, max_table_width=85, max_label_width=7)
produces
Number of Fruits in Basket
pears │*********** 10
grapes │************************************** 35
apples │*************************************************************** 58
pineapp │***************************************************************************** 70
└─────────────────────────────────────┰──────────────────────────────────────┐
0 35 70
Unicode Characters: Box Drawing
Assume all values are positive. As you start this problem, break it down into sub-problems and solve those individually. Create some wins for yourself. For example, how would you produce the row labels along the left-hand side? What other sub-problems exist? What should you tackle next?
This exercise brings together many different topics: functions, default parameters, math operations, variables, string methods, string formatting iteration, dictionaries