0

I have two lists and I want to place the two lists in a dictionary. I shuffled the second list. Now when I print the both list in dictionary then it works perfectly but the positions in dictionary changes when I try more than once.

import random
from random import shuffle
s = ['a','b','c','d']
l=[1,2,3,4]
shuffle(l)
b=dict(zip(s,l))
print(b)

Now the output for the first time is

{'a': 1, 'c': 3, 'b': 4, 'd': 2}

When I try second time I got

{'d': 1, 'c': 3, 'b': 2, 'a': 4}

Shuffling works fine but my problem is : I want to fix the key values positions a,b,c,d in dictionary and the only 1,2,3,4 should be shuffled. Is this possible using dictionaries..? What should I use to fix the keys and shuffle the values..

timansi
  • 19
  • 2
  • 2
    Dictionaries, by themselves, don't keep track or care about the order of their items. You might consider either an [`OrderedDict`](https://docs.python.org/3/library/collections.html#collections.OrderedDict) (which maintains the order in which you insert items), or iterating over a sorting of the keys. Either one would get you the keys ordered alphabetically when you printed, given your code. – jedwards Jul 20 '16 at 11:20
  • Thanks for your advice but when I use orderedDict with sorted the keys and values are arranged in the ascending order but I want to fix the key positions and I want to shuffle the values... – timansi Jul 20 '16 at 11:42
  • In that case, list of tuples (or) list of lists can be used – be_good_do_good Jul 20 '16 at 12:05

0 Answers0