Converting a dictionary into a list of Values/Tuples

Viewed 77

I’m trying to convert a dictionary into a list of values/tuples. I have this code:

list_to_sort = sorted(dictionary.items())
    lst = list(list_to_sort)
    print(lst)

The output is [('a', 9), ('b', 17), ('c', 17), ('d', 3)]. However, I want to switch the values to make the output this:

[(9, 'a'), (17, 'b'), (17, 'c'), (3, 'd')]

How do I do this?

5 Answers
[ (v,k) for k,v in sorted(D.items()) ]

You can just do this:

lst = [(val,key) for key,val in lst]

try this:

dict1 = {'a':9, 'b':17, 'c':17, 'd':3}
print([item[::-1] for item in sorted(dict1.items())])

Output:

[(9, 'a'), (17, 'b'), (17, 'c'), (3, 'd')]

Definitely, there is a better way to do this than what I'm suggesting, but try using the code below:

list_to_sort = sorted(dictionary.items())
lst = list( map(lambda x,y : (y,x) , list(list_to_sort)) )

plus, try it like this as well list( map(lambda x,y : (y,x) , list_to_sort) ). This is a bit cleaner but I'm not sure if it works 100%.

There is a variant:

d = {'b': 11, 'a': 14, 'd': 30, 'c': 17}
*res, = map(lambda x: (d[x], x), sorted(d))
print(res)

Output:

[(14, 'a'), (11, 'b'), (17, 'c'), (30, 'd')]
Related