Dictionaries for Tallying and Counting
1
CS 110
Reminders and Announcements
Announcements
This Week
Dictionaries (Cheat Sheet) - 01_dictionary_review.py
3
Create a dictionary | my_dict = {} |
Get element from a dictionary | my_dict.get(key) |
Add/replace items in dictionary | my_dict[key] = value |
Remove items from dictionary | my_dict[key].pop(index) |
Iterate through a dictionary | for key in my_dict:� print(key, my_dict[key]) |
Check if key exists in dictionary | if my_dict.get(key) is None… if key in my_dict… |
Dictionaries: When are they useful?
4
Example: Creating a Dictionary
eng2sp = {
'one': 'uno',
'two': 'dos',
'three': 'tres'
}
5
Keys�(left)
Values�(right)
Complex Lookup tables and crosswalks
Challenge: Write a program that allows users to either lookup a French translation for an English word, or add a new French translation.
6
Dictionaries: When are they useful?
7
8
Example: One Video → Dictionary
single_video = {
"title": "Rick Astley - Never Gonna Give You Up",
"channel": {
"name": "Rick Astley",
"subscribers_count": 4460000
},
"description": "The official video for Never Gonna Give You Up by Rick Astley",
"date_posted": "Nov 1, 2010",
"id": "dQw4w9WgXcQ",
"like_count": 18000000,
"comment_count": 2420791,
"comments": [
{"user": "YouTube", "text": "can confirm: he never gave us up"},
{"user": "JB_OldVoltBike", "text": "I got rickrolled by a link saying it got taken down."}
]
}
Dictionaries: When are they useful?
10
Dictionary counting algorithms
Dictionaries also help us to count and group things. Examples:
11
Tallying and Counting
How many times does each letter in the word supercalifragilisticexpialidocious appear?
The algorithm:
03_count_letters.py & Python Tutor