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 | del my_dict[key] |
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": "Cat Vibing To Ievan Polkka (Official Video HD) Cat Vibing To Music | Cat Vibing Meme",
"channel": {
"name": "Bilal Göregen",
"subscribers_count": 15800000
},
"description": "Cat Vibing To Ievan Polkka - Street Drummer With Vibing Cat Meme (full video) New Cat Meme Cat Vibing To Ievan Polkka (Official Video HD) Cat Vibing To Music | Cat Vibing Meme",
"date_posted": "Nov 1, 2020",
"url": "https://www.youtube.com/watch?v=NUYvbT6vTPs",
"like_count": 3200000,
"comment_count": 144634,
"comments": [
{"user": "JonJaded", "text": "The meme, the music, the guy, the cat...everything is perfect."},
{"user": "randomcradevr", "text": "A turkish man playing a Finiish song while a Canadian cat vibes."}
]
}
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