Created
June 25, 2021 05:25
-
-
Save ProfAvery/091d9fb71345b44799909a64df72b413 to your computer and use it in GitHub Desktop.
Fun with hash tables
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
students = [ | |
['foo', 'junior'], | |
['bar', 'senior'], | |
['baz', 'junior'], | |
['quux', 'junior'], | |
['guacamole', 'senior'], | |
['spatula', 'junior'], | |
['firewood', 'senior'], | |
] | |
ht = {} | |
for student in students: | |
name, level = student | |
print(f'Adding {name} to the list of {level}s...') | |
if level in ht: | |
names = ht[level] | |
print(f'Before: {names}') | |
names.append(name) | |
print(f'After: {names}') | |
ht[level] = names | |
else: | |
print(f'Before: []') | |
ht[level] = [name] | |
print(f'After: {ht[level]}') | |
print() | |
for level, names in ht.items(): | |
print(level) | |
for name in names: | |
print('\t', name) | |
ht = {} | |
for student in students: | |
name, level = student | |
print(f'Incrementing the number of {level}s...') | |
if level in ht: | |
count = ht[level] | |
print(f'Before: {count}') | |
count += 1 | |
print(f'After: {count}') | |
ht[level] = count | |
else: | |
print(f'Before: 0') | |
ht[level] = 1 | |
print(f'After: {ht[level]}') | |
print() | |
import pprint | |
pprint.pprint(ht) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment