Skip to content

Instantly share code, notes, and snippets.

@ProfAvery
Created June 25, 2021 05:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ProfAvery/091d9fb71345b44799909a64df72b413 to your computer and use it in GitHub Desktop.
Save ProfAvery/091d9fb71345b44799909a64df72b413 to your computer and use it in GitHub Desktop.
Fun with hash tables
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