GodSaveTheDucks
GodSaveTheDucks

Reputation: 756

Python: Lists to Dictionary

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!

Upvotes: 0

Views: 818

Answers (2)

ragardner
ragardner

Reputation: 1975

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

Upvotes: 0

Smart Manoj
Smart Manoj

Reputation: 5861

a=[2, 1, 3]
b=[31, 12, 5]
from collections import OrderedDict
print(OrderedDict(zip(a,b)))

Upvotes: 5

Related Questions