CS1033 Programming Fundamentals - Data Structures with Dictionaries

Introduction to Dictionary Data Structure

  • Dictionaries store data elements as key-value pairs, unlike lists, tuples, and sets that store each data element as a single value.

  • The key is used for optimized storage and efficient access to values.

  • Dictionaries are unordered collections where the key maps to the value, similar to a word and its explanation in a regular dictionary.

Creating Dictionaries

  • Two methods to create dictionaries in Python:

    1. Using curly brackets {}.

    2. Using the built-in function dict().

  • A dictionary can be created by grouping comma-separated data elements within curly {} brackets.

  • Each data element is a colon-separated key-value pair: key : value.

  • The key in a dictionary must be unique and immutable.

  • Values can be of any data type and can be duplicated.

  • To create an empty dictionary, use {} without any data elements inside.

Python Code Examples for Creating Dictionaries

  • Dictionaries commonly have a single data type for the key.

  • Example:
    python A = {1:"Newton’s method", 2:"Taylor’s theorem", 3:"L’Hopital’s rule"}
    *Note the use of different ways of specifying a string to deal with the apostrophe symbol.

  • Dictionaries can use mixed data types for the key.

  • Example:
    python B = {’1D’:"Curve", ’2D’:"Surface", 1:[’Point’, ’Line’, ’Plane’]}

  • key is used in dictionaries, not index.

  • Empty dictionaries can be easily created.

  • Examples:
    python C = {} D = dict()

  • Using a sequence (list) of pair-type tuples with the dict() function is a common and useful way to create dictionaries.

  • Example:
    python E = dict([(’imperative’, ’C’),(’functional’, ’Lisp’),(’procedural’, ’Pascal’)]) print(E)

  • Output:
    text {’imperative’: ’C’, ’functional’: ’Lisp’, ’procedural’: ’Pascal’}

Adding Elements to a Dictionary

  • Two methods to add elements in Python:

    1. Directly accessing data values using keys of a dictionary.

    2. Using the built-in function update().

  • Elements can be added by defining the key and the data value.

  • Example:
    python TT = {} TT[1] = ’Programming’ TT[2] = ’Mathematics’ TT[3] = ’Electrical’ print(TT)

  • Output:
    text {1: ’Programming’, 2: ’Mathematics’, 3: ’Electrical’}

  • Existing data values can be updated using an existing key with a new data value.

  • Example:
    python TT[4] = ’Mentoring’ print(TT) TT[4] = ’Online Mentoring’ print(TT)

  • Output:
    text {1: ’Programming’, 2: ’Mathematics’, 3: ’Electrical’, 4: ’Mentoring’} {1: ’Programming’, 2: ’Mathematics’, 3: ’Electrical’, 4: ’Online Mentoring’}

  • The update() function can be used to change dictionary contents.

  • Pass a dictionary or an iterable list of pairs as the argument to the update() method.

  • Dictionary values with matching keys from the passed argument will have their data value updated.

  • Example:
    python TT.update([(1, ’CS Programming’),(2, ’MA Maths’)]) print(TT)

  • Output:
    text {1: ’CS Programming’, 2: ’MA Maths’, 3: ’Electrical’, 4: ’Online Mentoring’}

  • If the passed argument has keys not present in the calling dictionary, those entries are added as new elements.

  • Example:
    python TT.update([(5, ’Mechanics’)]) print(TT)

  • Output:
    text {1: ’CS Programming’, 2: ’MA Maths’, 3: ’Electrical’, 4: ’Online Mentoring’, 5: ’CE Mechanics’}

Removing Elements from Dictionary

  • Four methods to remove elements in Python:

    1. Using the del keyword.

    2. Using the built-in function pop().

    3. Using the built-in function popitem().

    4. Using the built-in function clear().

  • Keys can be deleted using the del keyword.

  • Two ways to use del:

    1. Delete specific entries using keys.

    2. Delete the entire dictionary.

  • Once deleted, a dictionary is no longer available in the program.

  • An entry can be removed using pop() with the key as an argument.

  • pop() returns the value from the dictionary while deleting the entry.

  • popitem() returns an arbitrary element as a tuple (key, value) while deleting the full entry.

  • clear() deletes all items from a dictionary at once.

  • A cleared dictionary is still available in the program, unlike deletion with del.

  • Example of deleting a directory:
    python A = {1:’Alice’, 2:’Bob’, 3:’Charlie’, 4:’Dave’} print(A) del A print(A)

  • Output:
    text {1: ’Alice’, 2: ’Bob’, 3: ’Charlie’, 4: ’Dave’} Traceback (most recent call last): File "main.py", line 4, in <module> print(A) NameError: name ’A’ is not defined

  • Example of deleting a specific item:
    python B = {1:’Alice’, 2:’Bob’, 3:’Charlie’, 4:’Dave’, 5:{’Eve’:’Apple’, ’Frank’:’Huawei’}} print(B) del B[3] print(B)

  • Output:
    text {1: ’Alice’, 2: ’Bob’, 3: ’Charlie’, 4: ’Dave’, 5: {’Eve’: ’Apple’, ’Frank’: ’Huawei’}} {1: ’Alice’, 2: ’Bob’, 4: ’Dave’, 5: {’Eve’: ’Apple’, ’Frank’: ’Huawei’}}

  • Deleting a specific item in a nested directory:
    python del B[5][’Frank’] print(B)

  • Output:
    text {1: ’Alice’, 2: ’Bob’, 4: ’Dave’, 5: {’Eve’: ’Apple’}}

  • Using pop() function:
    python value = B.pop(2) print("Dictionary", B, "with item", value, "popped")

  • Output:
    text Dictionary {1: ’Alice’, 4: ’Dave’, 5: {’Eve’: ’Apple’}} with item Bob popped

  • Using popitem() function:
    python B[6] = ’George’ value = B.popitem() print("Dictionary", B, "with item", value, "popped") B.clear() print(B)

  • Output:
    text Dictionary {1: ’Alice’, 4: ’Dave’, 5: {’Eve’: ’Apple’}} with item (6, ’George’) popped {}

Accessing Elements from a Dictionary

  • Two methods to access elements:

    1. Using the key as the index within square brackets [].

    2. Using the built-in function get().

  • Example using key as index:
    python storage = {1:’Register’, 2:’Cache’, 3:’Memory’, 4:’Disk’} print(storage[2])

  • This method gives a run-time error if the key does not exist.

  • get() does not return an error if a matching key is not found.

  • Example:
    python print(storage.get(2)) storage[5] = ’None’ print(storage.get(5)) print(storage.get(6))

  • Accessing elements of a nested dictionary:
    python storage.update([(2, {2.1:’L1Cache’, 2.2:’L2Cache’, 2.3:’L3Cache’})]) print(storage[2][2.2])

Python Code Execution for Dictionary Element Access

Cache
Cache
None
None
L2Cache

Useful Python Functions for Dictionary

  • len() returns the number of items in the dictionary.

  • keys() returns a new object containing the set of keys.

  • values() returns a new object containing the set of values.

  • items() returns a new object containing the set of items (tuples).

  • copy() returns a shallow copy of the dictionary.

  • sorted() returns a new sorted list of keys in the dictionary.

  • fromkeys() takes a sequence of items as the first argument and an optional value as the second argument to create a new dictionary.

  • setdefault() returns the corresponding value if the key is in the dictionary; otherwise, it inserts the key with a specified value (or None if no value is given).

Python Code Samples for Collection of Functions

A = {1: 'A', 2: 'B', 3: {3.1: 'C.a', 3.2: 'C.b'}, 4:'D'}
print('Dictionary A is: \n',A)
print('Length of Dictionary A: ',len (A))
A_keys = A.keys()
print('Keys in Dictionary A: \n',A_keys)
A_values = A. values()
print('Values in Dictionary A:\n',A_values)
A_items = A.items()
print('Items in Dictionary A:\n',A_items)
B = A.copy()
print('Dictionary B is: \n',B)
A.update([(5,'E')])
print('Dictionary A is: \n',A)
print('Dictionary B is: \n',B)
origins = {'bats': True, 'civets': True, 'camels': True, 'cats': False}
print('Dictionary origins is: \n', origins)
sorted_origins = sorted(origins)
print('Dictionary origins sorted:\n', sorted_origins)
new_origins = origins. fromkeys (['cats', 'civets'], True)
print('Dictionary new origins: \n',new_origins)
new_origins.setdefault('pangolin', False)
print('Dictionary new origins: \n', new_origins)

Python Code Execution for Collection of Functions

Dictionary A is:
{1: 'A', 2: 'B', 3: {3.1: 'C.a', 3.2: 'C.b'}, 4: 'D'}
Length of Dictionary A: 4
Keys in Dictionary A:
dict_keys([1, 2, 3, 4])
Values in Dictionary A:
dict_values(['A', 'B', {3.1: 'C.a', 3.2: 'C.b'}, 'D'])
Items in Dictionary A:
dict_items([(1, 'A'), (2, 'B'), (3, {3.1: 'C.a', 3.2: 'C.b'}), (4, 'D')])
Dictionary B is:
{1: 'A', 2: 'B', 3: {3.1: 'C.a', 3.2: 'C.b'}, 4: 'D'}
Dictionary A is:
{1: 'A', 2: 'B', 3: {3.1: 'C.a', 3.2: 'C.b'}, 4: 'D', 5: 'E'}
Dictionary B is:
{1: 'A', 2: 'B', 3: {3.1: 'C.a', 3.2: 'C.b'}, 4: 'D'}
Dictionary origins is:
{'bats': True, 'civets': True, 'camels': True, 'cats': False}
Dictionary origins sorted:
['bats', 'camels', 'cats', 'civets']
Dictionary new origins:
{'cats': True, 'civets': True}
Dictionary new origins:
{'cats': True, 'civets': True, 'pangolin': False}

Summary: Sets vs. Dictionaries

  • Sets are created using curly brackets: {1,2,3,4,5,1,2,3,4,5}.

  • Duplicate values in sets are automatically removed.

  • Dictionaries are created similarly, but elements must have the key specified: {1:1, 2:2, 3:3, 4:4, 5:5, 6:1, 7:2, 8:3, 9:4, 10:5}.

  • Keys in dictionaries must be unique, while values can be duplicated.

  • Duplicate keys are automatically removed.

  • Similarities:

    • Both cannot have duplicate elements.

    • Both are mutable (elements can be added and removed).

  • Differences:

    • Data elements in sets are immutable (e.g., no sets of lists).

    • Data elements in dictionaries can be mutable (e.g., dictionaries of lists with unique keys).

Python Code Examples for Summary

A = {1,2,3,4,5,1,2,3,4,5}
print("Set:",A)
B = {1:1,2:2,3:3,4:4,5:5,6:1,7:2,8:3,9:4,10:5}
print("Dictionary:",B)
C = {1:1,2:2,3:3,4:4,5:5,6:1,7:2,8:3,9:4,9:5}
print("Dictionary with duplicate key:",C)
D = {’a’,’b’,’c’,’d’,’e’}
print("Set of strings:",D)
E = {1:’a’,2:’b’,3:’c’,4:’d’,5:’e’}
print("Dictionary of strings:",E)
F = {’a’:[1,2,3],’b’:[4,5,6]}
print("Dictionary of lists:",F)
# below code will give a "type error"
G = {[1,2,3],[4,5,6]}
print("Set of lists:",G)

Exercise: Covid-19 Pandemic App

  • Develop an app to help people confined to their homes during the Covid-19 pandemic.

  • Residents send requests with their mobile number, address, and a food item to a central database.

  • The database should be implemented as a Python dictionary data structure.

  • Process the database to create a delivery plan dictionary.

  • The delivery plan allows traders to quickly find the list of items required by residents in a particular address.

Sample Program Execution for the Exercise

The database has 9 records
777666123: {'Molpe Road, Katubedda': 'Rice'}
712444321 : {'Anandarama Road, Katubedda': 'Coconut Oil'}
777666456 : ['Molpe Road, Katubedda': 'Sugar'}
712444654 : {'Anandarama Road, Katubedda': 'Milk Powder'}
777666789: ['Molpe Road, Katubedda': 'Flour'}
712444987 : {'Anandarama Road, Katubedda': 'Tea Leaves'}
712876123: {'Anandarama Road, Katubedda': 'Rice'}
712567431 : ['Molpe Road, Katubedda': 'Flour'}
712876994 : {'First Lane, Katubedda': 'Coconuts'}

Residents in Molpe Road, Katubedda want to purchase
{'Sugar', 'Flour', 'Rice'}
Residents in Anandarama Road, Katubedda want to purchase
{'Coconut Oil', 'Tea Leaves', 'Milk Powder', 'Rice'}
Residents in First Lane, Katubedda want to purchase
{'Coconuts'}