0

I'm writing this question despite the many answers on stackoverflow as the solutions did not work for my problem.
I have 2 Lists, List1 and List2. When I dict(zip(List1,List2)) the order of the elements inside the dictionary are disturbed.

print s_key
print value
sorted_dict = {k: v for k,v in zip(s_key,value)}
another_test = dict(zip(s_key,value))
print sorted_dict
print another_test
print zip(s_key,value))

Terminal :

[2, 1, 3]
[31, 12, 5]
{1: 12, 2: 31, 3: 5}
{1: 12, 2: 31, 3: 5}
[(2, 31), (1, 12), (3, 5)]

I was under the impression that the [(2, 31), (1, 12), (3, 5)] would be converted to a dict

Any help to understand where or what I'm doing wrong would help! Thanks!

GodSaveTheDucks
  • 756
  • 5
  • 19
  • 8
    dicts are unordered. If you need a particular order, use [`OrderedDict`](https://docs.python.org/2/library/collections.html#collections.OrderedDict). – khelwood Apr 25 '17 at 11:23
  • You can't sort a dictionary like this. I would recommend reading about hash tables – user3684792 Apr 25 '17 at 11:23

2 Answers2

5
a=[2, 1, 3]
b=[31, 12, 5]
from collections import OrderedDict
print(OrderedDict(zip(a,b)))
Smart Manoj
  • 5,230
  • 4
  • 34
  • 59
0

You cannot sort a dictionary, in your case if you wanted to display sorted key/values of your dictionary you can convert it to a list of tuples as you have and sort it by whichever element you want. In the code below it creates a list of tuples and sorts by the first element in the tuples:

l1,l2=[2, 1, 3],[31, 12, 5]
print ([(one,two) for (one,two) in
        sorted(zip(l1,l2),key=lambda pair: pair[0])])

prints:

[(1, 12), (2, 31), (3, 5)]

shoutout to Sorting list based on values from another list? for the help

Either that or create a list of the dictionaries keys and sort the list then loop through the list and call each key

Or use ordered dict as others have pointed out

Community
  • 1
  • 1
ragardner
  • 1,836
  • 5
  • 22
  • 45