0% found this document useful (0 votes)
15 views53 pages

Week 3 - Lect 1 Dictionary Class

The document provides an overview of Python dictionaries, detailing their characteristics, creation methods, and operations such as accessing, updating, and deleting key-value pairs. It explains the importance of hashable keys, the use of dictionary comprehensions, and various methods for populating and retrieving data from dictionaries. Additionally, it covers advanced features like the .fromkeys() method and the use of membership operators.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views53 pages

Week 3 - Lect 1 Dictionary Class

The document provides an overview of Python dictionaries, detailing their characteristics, creation methods, and operations such as accessing, updating, and deleting key-value pairs. It explains the importance of hashable keys, the use of dictionary comprehensions, and various methods for populating and retrieving data from dictionaries. Additionally, it covers advanced features like the .fromkeys() method and the use of membership operators.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

Dictionary

Week 3

Dr. Syed Imran Ali


Agenda
• Dictionary Data Structure
• Dict creation approaches
• Accessing values
• Deletion operations
• Other general purpose operations

Advanced Programming in Python 2


Dictionary
• A dictionary is a built-in data type used to store data in key-value pairs. It
is a mutable, ordered collection that does not allow duplicate keys.

>>> config = { >>> # Update a value


... "color": "green", >>> config["font"] = "Helvetica"
... "width": 42, >>> config
... "height": 100, {
... "font": "Courier", 'color': 'green',
... } 'width': 42,
'height': 100,
>>> # Access a value through its key 'font': 'Helvetica'
>>> config["color"] }
'green'

Advanced Programming in Python 3


Dictionary
• Python’s dictionaries have the following characteristics:
• Mutable: The dictionary values can be updated in place.
• Dynamic: Dictionaries can grow and shrink as needed.
• Efficient: They’re implemented as hash tables, which allows for fast
key lookup.
• Ordered: Starting with Python 3.7, dictionaries keep their items in the
same order they were inserted.
• The keys of a dictionary have a couple of restrictions. They need
to be:
• Hashable: This means that you can’t use unhashable objects like lists
as dictionary keys.
• Unique: This means that your dictionaries won’t have duplicate keys.
Advanced Programming in Python 4
Creating Dictionaries in Python - Literals
• The most common way is to use dictionary literals, which are a comma-
separated series of key-value pairs in curly braces.

{
<key_1>: <value_1>,
<key_2>: <value_2>,
...,
<key_N>: <value_N>,
}

Advanced Programming in Python 5


Keys are Hashables
• The keys must be hashable objects like numbers, strings,
or tuples.
• Being hashable means they can be passed to a hash
function.
• A hash function takes data of arbitrary size and maps it
to a fixed-size value called a hash value—or just hash—
which is used for table lookup and comparison.
• In Python, the built-in immutable data types are
hashable, and the mutable types are unhashable.

Advanced Programming in Python 6


Creating Dictionaries in Python - Literals
• The following code defines a dictionary that maps cities or states to the
names of their corresponding Major League Baseball (MLB) teams

>>> MLB_teams = {
... "Colorado": "Rockies",
... "Chicago": "White Sox",
... "Boston": "Red Sox",
... "Minnesota": "Twins",
... "Milwaukee": "Brewers",
... "Seattle": "Mariners",
... }
Advanced Programming in Python 7
Creating Dictionaries in Python - Literals
• The following example shows a dictionary with integer,
float, and Boolean objects used as keys

>>> {42: "aaa", 2.78: "bbb", True: "ccc"}


{42: 'aaa', 2.78: 'bbb', True: 'ccc'}

Advanced Programming in Python 8


Creating Dictionaries in Python - Literals
You can even use objects like data types and functions as
keys

>>> types = {int: 1, float: 2, bool: 3}


>>> types
{<class 'int'>: 1, <class 'float'>: 2, <class 'bool'>: 3}

>>> types[float]
2
>>> types[bool]
3
Advanced Programming in Python 9
Creating Dictionaries in Python - Literals
• Unhashable objects as keys

>>> {[1, 2]: "A list as a key? Hmm..."}


Traceback (most recent call last):
...
TypeError: unhashable type: 'list'

Advanced Programming in Python 10


Creating Dictionaries in Python - Literals
• Even though tuples are immutable, they can contain
mutable objects. You can’t use a tuple that contains
mutable objects as a dictionary key

>>> {(1, [1, 1]): "a"}


Traceback (most recent call last):
...
TypeError: unhashable type: 'list'

Advanced Programming in Python 11


Dictionary Creation
• If you need to use sequences as dictionary keys, then you can use
tuples because tuples are immutable

>>> a_dict = {(1, 1): "a", (1, 2): "b", (2, 1): "c", (2, 2): "d"}

>>> a_dict[(1, 1)]


'a'
>>> a_dict[(2, 1)]
'c'

Advanced Programming in Python 12


Custom objects as values
>>> class Point:
... def __init__(self, x, y):
... self.x = x
... self.y = y
...

>>> {
... "colors": ["red", "green", "blue"],
... "plugins": {"py_code", "dev_sugar", "fasting_py"},
... "timeout": 3,
... "position": Point(42, 21),
... }
Advanced Programming in Python 13
Creating Dictionaries in Python - Constructor
• The arguments to dict() can be a series of keyword
arguments, another mapping, or an iterable of key-value
pairs.

dict()
dict(**kwargs)
dict(mapping, **kwargs)
dict(iterable, **kwargs)

Advanced Programming in Python 14


dict(**kwargs) – variable = value

>>> MLB_teams = dict(


... Colorado="Rockies",
... Chicago="White Sox",
... Boston="Red Sox",
... Minnesota="Twins",
... Milwaukee="Brewers",
... Seattle="Mariners",
... )

Advanced Programming in Python 15


Through iterable
>>> MLB_teams = dict(
... [
... ("Colorado", "Rockies"),
... ("Chicago", "White Sox"),
... ("Boston", "Red Sox"),
... ("Minnesota", "Twins"),
... ("Milwaukee", "Brewers"),
... ("Seattle", "Mariners"),
... ]
... )
Advanced Programming in Python 16
Through zip function

>>> dict(zip(places, teams))


>>> places = [ >>> teams = [
{
... "Colorado", ... "Rockies",
'Colorado': 'Rockies',
... "Chicago", ... "White Sox",
'Chicago': 'White Sox',
... "Boston", ... "Red Sox",
'Boston': 'Red Sox',
... "Minnesota", ... "Twins",
'Minnesota': 'Twins',
... "Milwaukee", ... "Brewers",
'Milwaukee': 'Brewers',
... "Seattle", ... "Mariners",
'Seattle': 'Mariners'
... ] ... ]
}

Advanced Programming in Python 17


Dictionary Creation - .fromkey() method
The dict data type has a class method called .fromkeys() that
lets you create new dictionaries from an iterable of keys and
a default value. The method’s signature looks like the
following

.fromkeys(iterable, value=None, /)

Advanced Programming in Python 18


Dictionary Creation - .fromkey() method
The dict data type has a class method called .fromkeys() that lets you
create new dictionaries from an iterable of keys and a default value.
The method’s signature looks like the following

>>> inventory = dict.fromkeys(["apple", "orange", "banana", "mango"], 0)

>>> inventory
{'apple': 0, 'orange': 0, 'banana': 0, 'mango': 0}

Advanced Programming in Python 19


Accessing Dictionary Values
If you refer to a key that isn’t in the dictionary, then Python raises an
exception

>>> MLB_teams["Indianapolis"]
Traceback (most recent call last):
...
KeyError: 'Indianapolis'

Advanced Programming in Python 20


Accessing Dictionary Values
Accessing nested objects

>>> person = { >>> person["children"][0]


... "first_name": "John", 'Ralph'
... "last_name": "Doe", >>> person["children"][2]
... "age": 35, 'Bob'
... "spouse": "Jane",
... "children": ["Ralph", "Betty", "Bob"], >>> person["pets"]["dog"]
... "pets": {"dog": “Jimmy", "cat": "Sox"}, ‘Jimmy'
... } >>> person["pets"]["cat"]
'Sox'

Advanced Programming in Python 21


Populating Dictionaries

When populating dictionaries, there are three


common techniques that you can use. You can:

• Assign keys manually


• Add keys in a for loop
• Build a dictionary with a comprehension

Advanced Programming in Python 22


Assign keys manually

>>> person = {}

>>> person["first_name"] = "John"


>>> person["last_name"] = "Doe"
>>> person["age"] = 35
>>> person["spouse"] = "Jane"
>>> person["children"] = ["Ralph", "Betty", "Bob"]
>>> person["pets"] = {"dog": “Jimmy", "cat": "Sox"}

Advanced Programming in Python 23


Adding Keys in a for loop

>>> squares = {}

>>> for integer in range(1, 10):


... squares[integer] = integer**2
...

>>> squares
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}

Advanced Programming in Python 24


Building Dict with Comprehensions
Python has dictionary comprehensions, which is
another great tool for creating and populating
dictionaries with concise syntax.

>>> squares = {integer: integer**2 for integer in range(1, 10)}


>>> squares
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}

Advanced Programming in Python 25


Retrieving Data From Dictionaries
The .get() method provides a convenient way to retrieve the value
associated with a key without checking whether the key exists beforehand.

>>> inventory = {"apple": 100, "orange": 80, "banana": 100}

>>> inventory.get("apple")
100
>>> print(inventory.get("mango"))
None

Advanced Programming in Python 26


Retrieving Data From Dictionaries
The key you want to search for is the first argument to .get(). The
second argument, which is optional, is a default value that will be
used if the target key doesn’t exist in the dictionary.

>>> inventory.get("mango", 0)
0

Advanced Programming in Python 27


Retrieving All the Values: .values()
The dict_values object contains all the values in inventory. Note that any
duplicate values will be returned as many times as they occur

>>> inventory = {"apple": 100, "orange": 80, "banana": 100}

>>> inventory.values()
dict_values([100, 80, 100])

Advanced Programming in Python 28


Accessing All the Keys: .keys()
Again, the view object dict_keys contains all the keys in the inventory
dictionary. Since dictionary keys are unique, you won’t get any duplicate
keys

>>> inventory = {"apple": 100, "orange": 80, "banana": 100}

>>> inventory.keys()
dict_keys(['apple', 'orange', 'banana'])

Advanced Programming in Python 29


Getting All the Items or Key-Value Pairs: .items()
The .items() method returns a dictionary view containing tuples of keys and
values. The first item in each tuple is the key, while the second item is the
associated value

>>> inventory = {"apple": 100, "orange": 80, "banana": 100}

>>> inventory.items()
dict_items([('apple', 100), ('orange', 80), ('banana', 100)])

Advanced Programming in Python 30


Adding Key-Value Pairs and Updating Dictionaries
>>> inventory = {"apple": 100, "orange": 80}

>>> inventory.setdefault("apple")
100
>>> print(inventory.setdefault("mango"))
None
>>> inventory
{'apple': 100, 'orange': 80, 'mango': None}
>>> inventory.setdefault("banana", 0)
0
>>> inventory
{'apple': 100, 'orange': 80, 'mango': None, 'banana': 0}
Advanced Programming in Python 31
Updating a Dict: .update([other])
The .update() method merges a dictionary with another dictionary
or with an iterable of key-value pairs.

If other is a dictionary, then a_dict.update(other) merges the


entries from other into a_dict. For each key in other, you can have
one of the following results:

• If the key isn’t present in a_dict, then the key-value pair from
other is added to a_dict.
• If the key is present in a_dict, then the corresponding value in
a_dict is updated to the value in other
Advanced Programming in Python 32
PEP
>>>8config
– Python
={ Coding Style Guide
... "color": "green", >>> config.update(user_config)
... "width": 42,
... "height": 100, >>> config
... "font": "Courier", {
... } 'color': 'red',
'width': 42,
>>> user_config = { 'height': 100,
... "path": "/home", 'font': 'Arial',
... "color": "red", 'path': '/home',
... "font": "Arial", 'position': (200, 100)
... "position": (200, 100), }
... }
Advanced Programming in Python 33
Updating a Dict: .update([other])
The other argument may also be a sequence of key-value pairs
>>> config.update([("width", 200), ("api_key", 1234)])
>>> config
{
'color': 'red',
'width': 200,
'height': 100,
'font': 'Arial',
'path': '/home',
'position': (200, 100),
'api_key': 1234
}
Advanced Programming in Python 34
Updating a Dict: .update([other])
Finally, you can also call .update() with keyword arguments
>>> config.update(color="yellow", script="__main__.py")
>>> config
{
'color': 'yellow',
'width': 200,
'height': 100,
'font': 'Arial',
'path': '/home',
'position': (200, 100),
'api_key': 1234,
'script': '__main__.py'
} Advanced Programming in Python 35
Removing items through pop()
>>> inventory = {"apple": 100, "orange": 80, "banana": 100}

>>> inventory.pop("apple")
100
>>> inventory
{'orange': 80, 'banana': 100}

>>> inventory.pop("mango")
Traceback (most recent call last):
...
KeyError: 'mango'

>>> inventory.pop("mango", 0)
0 Advanced Programming in Python 36
Removing items through popitem()

>>> inventory = {"apple": 100, >>> inventory.popitem()


"orange": 80, "banana": 100} ('orange', 80)
>>> inventory
>>> inventory.popitem() {'apple': 100}
('banana', 100)
>>> inventory >>> inventory.popitem()
{'apple': 100, 'orange': 80} ('apple', 100)
>>> inventory
{}

Advanced Programming in Python 37


Using Operators with Dictionaries

There are a few Python operators you can use with dictionaries.
The most notable ones are the membership, equality, and union
operators.

Membership: in and not in


• The membership operators in and not in allow you to
determine whether a given key, value, or item is in a
dictionary, depending on the target iterable you use

Advanced Programming in Python 38


Membership operators
>>> MLB_teams = { >>> MLB_teams = {
... "Colorado": "Rockies", ... "Colorado": "Rockies",
... "Chicago": "White Sox", ... "Chicago": "White Sox",
... "Boston": "Red Sox", ... "Boston": "Red Sox",
... "Minnesota": "Twins", ... "Minnesota": "Twins",
... "Milwaukee": "Brewers", ... "Milwaukee": "Brewers",
... "Seattle": "Mariners", ... "Seattle": "Mariners",
... } ... }

>>> "Milwaukee" in MLB_teams >>> "Milwaukee" in MLB_teams.keys()


True True
>>> "Indianapolis" in MLB_teams >>> "Indianapolis" in MLB_teams.keys()
False False
Advanced Programming in Python 39
Membership operators

You can also use the in and not in operators with the .values()
method to determine whether a given value is in your
dictionary
>>> "Rockies" in MLB_teams.values()
True
>>> "Rockies" not in MLB_teams.values()
False

Advanced Programming in Python 40


Membership operators

You may want to know whether a key-value pair is in the target


dictionary. To figure this out, you can use the membership
operators with the .items() method.

>>> ("Boston", "Red Sox") in MLB_teams.items()


True
>>> ("Boston", "Red Sox") not in MLB_teams.items()
False

Advanced Programming in Python 41


Equality and Inequality: == and !=
The equality (==) and inequality (!=) operators also work with
dictionaries. These operators disregard element order when you
use them with dictionaries, which is different from what
happens with lists.
>>> [1, 2, 3] == [3, 2, 1]
False
>>> {1: 1, 2: 2, 3: 3} == {3: 3, 2: 2, 1: 1}
True

>>> [1, 2, 3] != [3, 2, 1]


True
>>> {1: 1, 2: 2, 3: 3} != {3: 3, 2: 2, 1: 1}
False Advanced Programming in Python 42
Built-in functions
• all() Returns True if all the items in an iterable are truthy and False
otherwise.
• any() Returns True if at least one element in the iterable is truthy and
False otherwise.
• len() Returns an integer representing the number of items in the
input object.
• max() Returns the largest value in an iterable or series of arguments.
• min() Returns the smallest value in an iterable or series of arguments.
• sorted() Returns a new sorted list of the elements in the iterable.
• sum() Returns the sum of a start value and the values in the input
iterable from left to right.

Advanced Programming in Python 43


Checking for Truthy Data in Dictionaries: all() and any()
• You have a dictionary that maps products to their amounts. You
want to know whether all of the products are stocked.
>>> inventory = {"apple": 100, "orange": 80, "banana": 100, "mango":
200}

>>> all(inventory.values())
True

>>> # Update the stock


>>> inventory["mango"] = 0
>>> all(inventory.values())
False Advanced Programming in Python 44
Items: len()
• You need to know the number of key-value pairs in an existing
dictionary.
>>> MLB_teams = {
... "Colorado": "Rockies",
... "Chicago": "White Sox",
... "Boston": "Red Sox",
... "Minnesota": "Twins",
... "Milwaukee": "Brewers",
... "Seattle": "Mariners",
... }

>>> len(MLB_teams)
6
Advanced Programming in Python 45
Min() and Max() operations

>>> computer_parts = {
... "CPU": 299.99,
... "Motherboard": 149.99,
... "RAM": 89.99, >>> min(computer_parts.values())
... "GPU": 499.99, 59.99
... "SSD": 129.99,
... "Power Supply": 79.99, >>> max(computer_parts.values())
... "Case": 99.99, 499.99
... "Cooling System": 59.99,
... }

Advanced Programming in Python 46


Sorting based on Value

>>> dict(sorted(students.items(),
>>> students = {
... "Alice": 89.5, key=lambda item: item[1]))
... "Bob": 76.0, {
... "Charlie": 92.3, 'George': 73.4,
... "Diana": 84.7, 'Bob': 76.0,
... "Ethan": 88.9, 'Hannah': 81.2,
... "Fiona": 95.6, 'Diana': 84.7,
... "George": 73.4, 'Ethan': 88.9,
... "Hannah": 81.2, 'Alice': 89.5,
... } 'Charlie': 92.3,
'Fiona': 95.6
}
Advanced Programming in Python 47
Sorting based on Key

>>> dict(sorted(students.items(),
>>> students = { key=lambda item: item[0]))
... "Alice": 89.5, {
... "Bob": 76.0, 'Alice': 89.5,
... "Charlie": 92.3, 'Bob': 76.0,
... "Diana": 84.7, 'Charlie': 92.3,
... "Ethan": 88.9, 'Diana': 84.7,
... "Fiona": 95.6, 'Ethan': 88.9,
... "George": 73.4, 'Fiona': 95.6,
... "Hannah": 81.2, 'George': 73.4,
... } 'Hannah': 81.2
}
Advanced Programming in Python 48
Sum function

>>> daily_sales = {
... "Monday": 1500,
... "Tuesday": 1750,
... "Wednesday": 1600,
... "Thursday": 1800,
... "Friday": 2000,
... "Saturday": 2200,
... "Sunday": 2100,
... }

>>> sum(daily_sales.values()) / len(daily_sales)


1850.0
Advanced Programming in Python 49
Iterating over a dictionary
>>> students = {
... "Alice": 89.5,
... "Bob": 76.0,
... "Charlie": 92.3,
... "Diana": 84.7,
... "Ethan": 88.9,
... "Fiona": 95.6,
... "George": 73.4,
... "Hannah": 81.2,
... }

>>> for student in students:


... print(student)
Advanced Programming in Python 50
Iterating over a dictionary

>>> for student in students:


... print(student, "->", students[student])
...
Alice -> 89.5
Bob -> 76.0
Charlie -> 92.3
Diana -> 84.7
Ethan -> 88.9
Fiona -> 95.6
George -> 73.4
Hannah -> 81.2

Advanced Programming in Python 51


Iterating over a dictionary

>>> MLB_teams = { >>> for team in MLB_teams.values():


... "Colorado": "Rockies", ... print(team)
... "Chicago": "White Sox", ...
... "Boston": "Red Sox", Rockies
... "Minnesota": "Twins", White Sox
... "Milwaukee": "Brewers", Red Sox
... "Seattle": "Mariners", Twins
... } Brewers
Mariners

Advanced Programming in Python 52


Iterating over a dictionary

>>> for place, team in MLB_teams.items():


... print(place, "->", team)
...
Colorado -> Rockies
Chicago -> White Sox
Boston -> Red Sox
Minnesota -> Twins
Milwaukee -> Brewers
Seattle -> Mariners

Advanced Programming in Python 53

You might also like