0

So here is the code and I would like to print out the variables from the dictionary in a different order how do I do that?

    phonebook = {}

    line = input('Name and clour: ')
    while line:
     name, color = line.split()
     phonebook[name] = color 
     line = input('Name and clour: ')
    for x, y in phonebook.items():
    print(x, y) 
MFerguson
  • 1,739
  • 9
  • 17
  • 30
RTME SUPER
  • 21
  • 8

1 Answers1

0

Note that the dictionary is not ordered by insertion order, because it is implemented as a hash table. If you would still like to shuffle its order, you could convert its keys into a list and then shuffle it - You will not be able to use it as a dictionary since the order will be restored:

import random
keys =  list(phonebook.keys())
random.shuffle(keys)
new_phonebook_list_of_tuples = [(key, phonebook[key]) for key in keys]
AdamGold
  • 4,941
  • 4
  • 29
  • 47
  • Note that Python dictionaries are now insertion ordered as a language feature from Python 3.7+ (logically 3.6 in most/all cases, though it wasn't guaranteed) https://stackoverflow.com/questions/39980323/are-dictionaries-ordered-in-python-3-6 – ti7 Nov 20 '21 at 22:47