CMPE 150
Introduction to Computing
Fall 2021
Created by Gökçe Uludoğan
### Dictionaries
* Created by placing dictionary items inside curly braces {} , separated by commas.
* Each item is expressed as a pair (key, value)
* Keys must be immutable.
```python
# empty dictionary
my_dict = {} # or dict()
# dictionary with integer keys
my_dict = {1: 'apple', 2: 'ball'}
# dictionary with mixed keys
my_dict = {'name': 'John', 1: [2, 4, 3]}
```
### Accessing Elements
* Keys are used to access values in a dictionary.
* inside square brackets []
* `KeyError` is raised in case a key is not found
* with get() method
* returns `None` if the key is not found.
```python
my_dict = {'name': 'Jack', 'age': 26}
print(my_dict['name']) # Output: Jack
print(my_dict.get('age')) # Output: 26
print(my_dict.get('address')) # Output None
print(my_dict['address']) # KeyError
```
### Modifying Elements
* Using an assignment operator
* New items can be added.
* Existing items can be updated.
```python
my_dict = {'name': 'Jack', 'age': 26}
my_dict['age'] = 27
print(my_dict)
my_dict['address'] = 'Downtown'
print(my_dict)
```
Output
```
{'age': 27, 'name': 'Jack'}
{'address': 'Downtown', 'age': 27, 'name': 'Jack'}
```
### Removing Elements
* pop() removes and returns a particular item.
* popitem() removes and returns an arbitrary item.
* clear() removes all items at once
```python
squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
print(squares.pop(4))
print(squares)
print(squares.popitem())
print(squares)
squares.clear()
print(squares)
```
Output
```
16
{1: 1, 2: 4, 3: 9, 5: 25}
(5, 25)
{1: 1, 2: 4, 3: 9}
{}
```
### Dictionary Methods
* items(): Return items in (key, value) format.
* keys(): Returns keys.
* values(): Returns values.
```python
marks = {'English': 0, 'Math': 0, 'Science': 0}
for item in marks.items():
print(item)
print(list(sorted(marks.keys())))
```
Output
```
('Math', 0)
('English', 0)
('Science', 0)
['English', 'Math', 'Science']
```
### Dictionary Comprehension
* A fancy way to create a new dictionary.
```python
squares = {x: x*x for x in range(6)}
print(squares)
```
Output
```
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
```
Equivalent to
```python
squares = {}
for x in range(6):
squares[x] = x*x
print(squares)
```
### Membership Test
* Whether a key is in a dictionary or not.
```python
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
print(1 in squares)
print(2 not in squares)
print(49 in squares)
```
Output
```
True
True
False
```
### Iterating Through a Dictionary
```python
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
for i in squares:
print(squares[i])
```
Output
```
1
9
25
49
81
```
### Iterating Through a Dictionary
```python
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
for k, v in squares.items():
print(v)
```
Output
```
1
9
25
49
81
```
### Iterating Through a Dictionary
```python
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
for v in squares.values():
print(v)
```
Output
```
1
9
25
49
81
```
### Sorting
```python
example = {0: 0, 1: -1, 3: 9, 5: 7, 7: 19, 9: 28}
print(sorted(example))
print(dict(sorted(example.items(), key=lambda item: item[1])))
```
Output
```
[0, 1, 3, 5, 7, 9]
{1: -1, 0: 0, 5: 7, 3: 9, 7: 19, 9: 28}
```