Python 06 Dictionary
Python 06 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 {}
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'
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])
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!
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
15
Functions and operators in Dictionary
16
Functions and operators in Dictionary
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}
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