MOBI BOOT CAMP CORP. logoLearning Buddy
  • SIGN IN
  • Introduction
  • Setup
  • 1A: Fundamental Building Blocks
  • 1B: Compound Statements
  • 2: Ordered Collection
  • 3: Unordered Collection
    • Dictionaries
    • Sets
    • Colab Exercise
  • 4: More Data types
  • 5: Iteration Constructs
  • 6: Other constructs
  • 7. Regex
  • 8. Date and Time
  • Revision
  • Practice Exercise
  • Titanic Workshop

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)

Dictionary Mapping

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.
CAUTION
  • 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:

  1. Initialize the dictionary.
  2. Update the salary key to 62000.
  3. Add a new key-value pair: "status": "Active".
  4. Delete the "department" key using the del keyword.
  5. 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:

  1. Initialize the dictionary.
  2. Find the name of the employee who earned the highest commission using the max() function with the custom key parameter key=commissions.get.
  3. 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
Privacy Policy | Terms & Conditions