COMP1531
2.2 - Python - Dictionaries
Python - Dictionaries
Lists are sequential containers of memory. Values are referenced by their integer index (key) that represents their location in an order
Python - Dictionaries
Dictionaries are associative containers of memory. Values are referenced by their string key that maps to a value
name
"sally"
age
18
height
"187cm"
Python - Dictionaries
Dictionaries are associative containers of memory. Values are referenced by their string key that maps to a value
userData = {}
userData["name"] = "Sally"
userData["age"] = 18
userData["height"] = "187cm"
print(userData)
{'name': 'Sally', 'age': 18, 'height': '187cm'}
dict_basic_1.py
Python - Dictionaries
There are a number of different ways we can construct and interact with dictionaries
userData = {
'name' : 'Sally',
'age' : 18,
'height' : '186cm', # Why a comma?
}
userData['height'] = '187cm'
print(userData)
{'name': 'Sally', 'age': 18, 'height': '187cm'}
dict_basic_2.py
Python - Dictionaries
Basic loops are over keys not values:
How would we modify this to print out the values instead?
userData = [
{
'name' : 'Sally',
'age' : 18,
'height' : '186cm',
}, {
'name' : 'Bob',
'age' : 17,
'height' : '188cm',
},
]
for user in userData:
print("Whole user: ", user)
for part in user:
print(f" {part}")
Whole user: {'name': 'Sally', 'age': 18, 'height': '186cm'}
name
age
height
Whole user: {'name': 'Bob', 'age': 17, 'height': '188cm'}
name
age
height
dict_loop.py
Python - Dictionaries
userData = {'name' : 'Sally','age' : 18, \
'height' : '186cm'}
for user in userData.items():
print(user)
print("====================")
for user in userData.keys():
print(user)
print("====================")
for user in userData.values():
print(user)
('name', 'Sally')
('age', 18)
('height', '186cm')
====================
name
age
height
====================
Sally
18
186cm
dict_loop_2.py
Python - Dictionaries
Optional Activity
Q. Write a python program that takes in a series of words from STDIN and outputs the frequency of how often each vowel appears
COMP1531 21T1 - 2.2 - Python - Dictionaries
By haydensmith
COMP1531 21T1 - 2.2 - Python - Dictionaries
- 477