Core Python / Dictionaries#
What is a dictionary in Python, and how is it different from other data structures like lists and tuples?
A dictionary is a data structure that stores values indexed by unique keys. Generally speaking, you should treat dictionaries as an unordered collection. In Python versions greater than 3.7, the entries are ordered based on their insertion order.
How do you create an empty dictionary in Python?
You can create an empty dictionary with the
{ }
literal or thedict()
with no arguments.What are the two main components of a dictionary in Python? Explain with an example.
The two main components are a key that has an associated value.
adict = { "university":"Duke", "major":"Financial Technology"} adict["university"] 'Duke'
How do you access the value associated with a specific key in a dictionary?
Use the
[]
operator with the key object between the brackets. You can also use theget()
function.What happens if you try to access a key that doesn’t exist in a dictionary?
Using the
[]
operator, aKeyError
occurs if the value does not exist.With
get()
,None
is returned if the value does not exist. You can provide a default value that will be returned if the key does not exist.adict = { "university":"Duke", "major":"Financial Technology"} label = adict.get("instructor","unknown") print(label) # display "unknown" to the console
How do you add a new key-value pair to an existing dictionary?
Use the
[]
operator with the assignment operator=
.adict = { "university":"Duke", "major":"Financial Technology"} adict["instructor"] = "Slankas" instr = adict.get("instructor","unknown") print(instr) # display "Slankas" to the console
How do you remove a key-value pair from a dictionary?
Use the
del
statement (keyword) with the correct key.del adict["instructor"] adict["instructor"] # Raises a KeyError help("del") # Displays the help text associated with the del statement
To remove all entries from a dictionary, use the
clear()
. You can also just assign an empty dictionary to the variable.How do you check if a specific key exists in a dictionary?
Use the
in
operator.adict = { "university":"Duke", "major":"Financial Technology"} "university" in adict # evaluates to True "instructor" in adict # evaluates to False
How do you get a list of all keys or all values in a dictionary?
Use the functions
keys()
andvalues()
. Both of these functions return an iterator which we can then iterate over using afor
loop. You can also immediately convert the iterator to a list.adict = { "university":"Duke", "major":"Financial Technology"} for v in adict.values(): # prints "Duke" and "Financial Technology" on separate lines print(v) key_list = list(adict.keys()) print(key_list) # displays ['university', 'major'] to the console
What function returns the number of elements in a dictionary?
len()
Note: This is the same function for strings, lists, and tuples.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?
Just one. If multiple values are needed, then the value needs to be a container (e.g., list) that can hold the multiple values. If try to add a duplicate key, the existing entry is replaced.
What are the requirements(limitations) for a dictionary key?
Keys can be any Python object (remember, everything in Python is an object) that is immutable.
Are dictionary entries unique?
No. Only keys are guaranteed to be unique.
How do you iterate over key-value pairs in a dictionary?
Use the
items()
function. The returns a tuple containing the key and value. We can also use tuple unpacking to directly assign the tuple entries to variables.adict = { "university":"Duke", "major":"Financial Technology"} for item in adict.items(): print("Key: {}, Name: {}".format(item[0], item[1])) for key, value in adict.items(): print("{}: {}".format(key, value))
How do you sort a dictionary by keys or values in Python?
By keys:
stock_prices = {'PG': 141.96, 'AXP': 154.42, 'AAPL': 137.13,'CSCO':43.49, 'HD':289.24, 'AMZN': 2538.23} for key in sorted(stock_prices): print("{}: Stock price: ${:,.2f}".format(key,stock_prices[key]))
By values:
stock_prices = {'PG': 141.96, 'AXP': 154.42, 'AAPL': 137.13,'CSCO':43.49, 'HD':289.24, 'AMZN': 2538.23} for key in sorted(stock_prices.values): print("{}: Stock price: ${:,.2f}".format(key,stock_prices[key]))
See the associated notebook (page) to reverse the sorted order or to provide a custom comparator.
How do you copy a dictionary in Python?
To copy a dictionary to a new object, use the
copy()
method, which creates a shallow copy that copies reference values, but not necessarily the objects to which those references point.s1 = {'AXP': 'American Express', 'AMGN': 'Amgen', 'AAPL': 'Apple'} s2 = s1.copy() s2['IBM'] = "International Business Machines" print(s1) # displays {'AXP': 'American Express', 'AMGN': 'Amgen', 'AAPL': 'Apple'} print(s2) # displays {'AXP': 'American Express', 'AMGN': 'Amgen', 'AAPL': 'Apple', 'IBM': 'International Business Machines'} s1.clear() print(s1) # displays {} print(s2) # displays {'AXP': 'American Express', 'AMGN': 'Amgen', 'AAPL': 'Apple', 'IBM': 'International Business Machines'}
What is the get() method in Python dictionaries, and how is it different from indexing with square brackets?
The
get()
retrieves values from dictionaries. Rather than raising aKeyError
if a key does not exist,None
is returned. An optional argument can also be specified to return a default value if a key does not exist.Can you have a dictionary as a value in another dictionary? If so, how would you access the nested dictionary?
Yes. This occurs quite frequently. Use repeating square bracket operators to access the nested dictionary.
company = {"symbol": "IBM", "name": "International Business Machines", "year_founded": 2140} companies = { "IBM": company} companies # evalutes to {'IBM': {'symbol': 'IBM', 'name': 'International Business Machines', 'year_founded': 2140}} companies["IBM"]["name"] # returns 'International Business Machines' companies["IBM"] # returns {'symbol': 'IBM', 'name': 'International Business Machines', 'year_founded': 2140}