Unordered Collection
In this lesson you will learn Dictionary and Set; the two data structures which are not considered a sequence.
Dictionaries
Dictionary is a set of key:value pairs in which the keys are unique. A pair of braces creates an empty dictionary: { }
Although in the latest implementation of Python, dictionary maintains the order of insert, it is considered an implementation detail and should not be relied upon as it may change in the future as per the official documentation.
Here is an example of dictionary with values:
country_codes = {
"US": "United States",
"UK": "United Kingdom",
"CA": "Canada",
"MX": "Mexico",
}
print(country_codes)

Sequences are indexed by range of numbers but dictionaries are indexed by keys. A key can be of any immutable type although using a string or a number is most common. Tuples can be used as keys as long as the elements of the tuples are immutable.
Here are some of common operations on Dictionaries
| Operations | Example | Output | Comments |
|---|---|---|---|
| Get value given a key | country_codes['US'] |
'United States' |
Dictionary keys are unique. Value can be any complex type including ordered or unordered collection |
| Change value for a key | country_codes['US'] = 'USA' print(country_codes['US']) |
'USA' |
Dictionaries are mutable so values can be changed |
| Delete a key del | del country_codes['US'] print(country_codes) |
{'UK': 'United Kingdom', 'CA': 'Canada', 'MX': 'Mexico'} |
A key/value pair is deleted |
| Get a list of keys keys() | keys = list(country_codes.keys()) print(keys) |
['UK','CA', 'MX'] |
You can check on the data type of keys by invoking print(type(keys)). You will notice that it is of type list |
| Construct a dict from list of tuples | dict([('UK', 'United Kingdom'),('MX','Mexico')]) |
{'MX': 'Mexico', 'UK': 'United Kingdom'} |
dict is one of the built in function |
| Construct a dict using arguments | dict(UK = 'United Kingdom', MX ='Mexico') |
{'MX': 'Mexico', 'UK': 'United Kingdom'} |
Keys have to be strings for this to work |
| Remove all elements clear() | state_codes = {'MI':'Michigan', 'IL':'Illinois'} state_codes.clear() print(state_codes) |
{} |
|
| Remove and get the element with specified key pop() | state_codes = {'MI':'Michigan', 'IL':'Illinois'} val = state_codes.pop('MI') print(val, state_codes) |
Michigan {'IL': 'Illinois'} |
This method returns the value of the popped key/value pair |
| Remove last key/value pair popitem() | state_codes = {'MI':'Michigan', 'IL':'Illinois'} item = state_codes.popitem() print(item, state_codes) |
('IL', 'Illinois') {'MI': 'Michigan'} |
This method returns the popped key/value pair as a tuple. Since dictionaries are unordered, any item can be popped when no key is provided. |
| Add a key/Value pair | country_codes['IN'] = 'India' print(country_codes) |
{'UK': 'United Kingdom', 'CA': 'Canada', 'IN':'India', 'MX': 'Mexico'} |
If the key is not present a new Key/Value pair is added. Else the existing value for the key is replaced. |
- If you try to access a key which is not present in the dictionary, KeyError is thrown
Getting the maximum key or value
You can get the largest key using the max function. This is straight forward. However if you want to get the key which holds the highest value then you would use the below expression
d1 = {"a": 1, "b": 5, "c": 10}
max(d1, key=d1.get)
Output:
'c'
Hands-on Exercises
Exercise 1: Update Employee Profile
Create a dictionary representing an employee's profile:
employee = {"id": 101, "name": "Sarah", "department": "Sales", "salary": 55000}
Write a Python program to:
- Initialize the dictionary.
- Update the
salarykey to62000. - Add a new key-value pair:
"status": "Active". - Delete the
"department"key using thedelkeyword. - Print the final dictionary.
# Write your code below and click Run Code
Click to view Answer
employee = {"id": 101, "name": "Sarah", "department": "Sales", "salary": 55000}
# Update salary
employee["salary"] = 62000
# Add key-value
employee["status"] = "Active"
# Delete key
del employee["department"]
print("Updated profile:", employee)
# Output: {'id': 101, 'name': 'Sarah', 'salary': 62000, 'status': 'Active'}
Exercise 2: Top Earner Lookup
You have a dictionary that maps employee names to their monthly sales commissions:
commissions = {"John": 1200, "Alice": 4500, "Bob": 3200, "Diana": 4100}
Write a Python program to:
- Initialize the dictionary.
- Find the name of the employee who earned the highest commission using the
max()function with the custom key parameterkey=commissions.get. - Print the top earner's name.
# Write your code below and click Run Code
Click to view Answer
commissions = {"John": 1200, "Alice": 4500, "Bob": 3200, "Diana": 4100}
# Find key with the highest value
top_earner = max(commissions, key=commissions.get)
print("Top earner is:", top_earner)
# Output: Top earner is: Alice