random.shuffle currently does not work on dictionaries (unless the keys happen to be integers in a range starting at 0):
>>> import random
>>> a = {0: 'dead parrot', 1: 'cat named Eric', 2: 'inverted piglet'}
>>> random.shuffle(a)
>>> print(a)
{0: 'cat named Eric', 1: 'dead parrot', 2: 'inverted piglet'}
>>> b = {'parrot': 'dead', 'cat': 'named Eric', 'piglet': 'inverted'}
>>> random.shuffle(b)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.12/random.py", line 357, in shuffle
x[i], x[j] = x[j], x[i]
~^^^
KeyError: 2
The idea is to modify random.shuffle to shuffle dictionary’s key/value pairs even if the keys don’t happen to be a range of integers.
An example program taking advantage of this:
#!/usr/bin/env python
# Read a letter-substitution cipher using your secret code!
alpha = {'A': 'A', 'B': 'B', 'C': 'C', 'D': 'D', 'E': 'E', 'F': 'F', 'G': 'G', 'H': 'H', 'I': 'I', 'J': 'J', 'K': 'K', 'L': 'L', 'M': 'M', 'N': 'N', 'O': 'O', 'P': 'P', 'Q': 'Q', 'R': 'R', 'S': 'S', 'T': 'T', 'U': 'U', 'V': 'V', 'W': 'W', 'X': 'X', 'Y': 'Y', 'Z': 'Z'}
enciphered = input('Enter the secret message to decode: ')
seed = input('Enter your secret code: ')
print('Secret decoder ring activated!')
random.Random(seed).shuffle(alpha)
plain = ''
for letter in enciphered:
plain += alpha[letter]
print('It says:', plain)
Edit: Fixed a typo in the code.