0% found this document useful (0 votes)
2 views

Python 06 Dictionary

The document provides an overview of dictionaries in Python, including how to create them, their features, and various functions and operators that can be used. It explains the structure of a dictionary, emphasizing the uniqueness of keys and the mutability of values. Additionally, it includes practical examples and exercises to reinforce understanding of dictionary operations.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Python 06 Dictionary

The document provides an overview of dictionaries in Python, including how to create them, their features, and various functions and operators that can be used. It explains the structure of a dictionary, emphasizing the uniqueness of keys and the mutability of values. Additionally, it includes practical examples and exercises to reinforce understanding of dictionary operations.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

DICTIONARY

Agenda

2
Agenda
• How to create Dictionary
• Functions and operators on Dictionary

3
Create Dictionary
• Dictionary is used to map or link the data you need
to store (value) and the key (key) you need to
retrieve that data.
• Dictionary in Python is defined as having two
components: key and value.
– A key is a unique object.
– The saved value can be a 1D List or 2D List, a string, a number, any
object in python...

4
Create Dictionary
• Create an empty dictionary: dict() or { }
d = dict() d = { }
print(d) # prints {} print(d) # prints {}

• Create a dictionary from a list of (key, value) pairs


pairs = [("cow", 5), ("dog", 98), ("cat", 1)]
d = dict(pairs)

print(d)

5
Create Dictionary
• Create a dictionary using static allocation
d = { "cow":5, "dog":98, "cat":1 }

print(d)

• Other examples:
d1 = {1: python.com',2: ‘ICT'}
d2 = {‘subject': ‘Python', 1: [2, 3, 5]}
d3 = dict({1:'apple', 2:'ball'})
d4 = dict([(1,’Rectangle'), (2,’Square')])

6
Features of the dictionary:
Things to note when using keys in dictionaries:
• A key cannot appear twice (keys cannot be duplicates).
• The value stored in the dictionary can be of any type while
the key must be an immutable type such as number, tuple
or string.
• Keys used in the dictionary are case sensitive - The same
key name but upper and lower case key names will be
considered different keys.

7
Features of the dictionary:
A dictionary maps a key to a value

ages = dict()
key = "tom"
value = 38
ages[key] = value # “tom" is the key, 38 is the value
print(ages)
print(ages[key])

8
Create Dictionary
• Keywords are represented as a set
– There is no order
d = dict()
d[2] = 100
d[4] = 200
d[8] = 300
print(d) # unpredictable order

– Unique
d = dict()
d[2] = 100
d[2] = 200
d[2] = 400
print(d) # { 2:400 }

9
Create Dictionary
• Keywords are represented as a set
– Keywords cannot be changed
d = dict()
a = [1] # lists are mutable, so...
d[a] = 42 # Error: unhashable type: 'list'

– Values are subject to change


d = dict(); a = [1,2]
d["fred"] = a ; print(d); print(d["fred"])
a += [3]
print(d["fred"])
# but keys may not be mutable
d[a] = 42 # TypeError: unhashable type: 'list'

10
Functions and operators in Dictionary

• Dictionary operations
– Find length: len()
d = { 1:[1,2,3,4,5], 2:"abcd" }
print(len(d)) # 2
– Make a copy: copy()
d1 = { 1:"a" }
d2 = d1.copy()
d1[2] = "b"
print(d1)
print(d2)
– Delete all elements in the dictionary: clear()
d = { 1:"a", 2:"b" }
d.clear()
print(d, len(d))

11
Functions and operators in Dictionary

• Dictionary operations
– Loop over dictionary: len()
d = { 1:"a", 2:"b" }
for key in d:
print(key, d[key])

– The in and not in operators:

d = { 1:"a", 2:"b" } d = { 1:"a", 2:"b" }


print(0 in d) # False print(0 not in d) # True
print(1 in d) # True print(1 not in d) # False
print("a" in d) # surprised? False print("a" not in d) # True

12
Functions and operators in Dictionary

• Dictionary operations
– Operator [key] : returns the value corresponding to the
key
d = { 1:"a", 2:"b" }
print(d[1]) # a
print(d[3]) # crash!

– Assignment operator = : assigns value to the


corresponding keyword
d = { 1:"a", 2:"b" }
print(d[1]) # a
d[1] = 42
print(d[1]) # 42

13
Functions and operators in Dictionary

• Dictionary operations
– function get(): get(key,default) returns the value
corresponding to the key or if it does not exist, returns
default ( None if default is not used)

d = { 1:"a", 2:"b" }
print(d.get(1)) # tuong duong d[1]
print(d.get(1, 42)) # default không được dùng
print(d.get(0)) # doesn't crash! Không bị lỗi
print(d.get(0, 42)) # default được dùng

14
Functions and operators in Dictionary

• Dictionary operations
– Function del(): removes a keyword from the dictionary
d = { 1:"a", 2:"b" }
print(1 in d) # True
del d[1]
print(1 in d) # False
del d[1] # crash! ERROR

– Change the value and add elements to the dictionary


d2 = {1: sbs.com’,’web’: ‘programming'}
d2[‘web'] = ‘django'
print(d2) #output: {1: ‘sbs.com’, ‘web': ‘django'}
d2[2] = 'Python‘
print(d2) #output: {1: ‘sbs.com’, ‘web': ‘django', 2: 'Python'}

15
Functions and operators in Dictionary

• Returns a list of objects using items() or keywords using keys()

• Sort keywords in dictionary

16
Functions and operators in Dictionary

 Update dictionary using: update()


d1 = { 1:"a", 2:"b" }
d2 = { 2:"c", 3:"d" }
d1.update(d2)
d2[4] = "e"
print(d1); print(d2)
 Dictionary comprehension
cube_number = {x: x*x*x for x in range(6)}
print(cube_number) # Output: {0: 0, 1: 1, 2: 8, 3: 27, 4: 64, 5: 125}

even_ cube_number = {x: x*x*x for x in range (10) if x%2==0}


print(even_ cube_number) # Output: {0: 0, 2: 8, 4: 64, 6: 216, 8: 512}

17
Convert between Data Types

print(float(11)) # 11.0
print(int(18.6)) # 18
print(set([2,4,6])) # set({2, 4, 6})
print(tuple({3,5,7})) # (3 , 5, 7)
print(list('hello’)) # ['h', 'e', 'l', 'l', 'o']
print(dict([[2,4],[1,3]])) # {1: 3, 2: 4}
print(dict([(3,9),(4,16)])) # {3: 9, 4: 16}

18
Practice with Dictionary
• IC1. Enter the variable s as your full name. Output the
dictionary variable d with the key being the character and
value being the number of occurrences.
s=“hello everyone” => d = {‘h’: 1, ‘e’: 4, ‘l’: 2, ‘o’: 2, ‘v’: 1, ‘r’: 1, ‘y’: 1, ‘n’: 1}
s=“khiet luong” => d = {‘k’: 1, ‘h’: 1, ‘i’: 1, ‘e’: 1, ‘t’: 1, ‘l’: 1, ‘u’: 1, ‘o’: 1,
‘n’: 1, ‘g’: 1}

• IC2. Given the following two dictionary variables:


price={“banana”: 4, “apple”: 2, “orange”: 1.5, “pear”: 3}
quantity={“banana”: 6, “orange”: 32, “pear”: 15}
Print out the order of fruits in a descending list of each type's
value (with value = quantity * price)

19
Homework
• Write a Python program to create a dictionary grouping a
sequence of key-value pairs into a dictionary of lists
• Original list:
('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
• Grouping a sequence of key-value pairs into a dictionary of
lists:
{'yellow': [1, 3], 'blue': [2, 4], 'red': [1]}

20

You might also like