user3150902
user3150902

Reputation: 73

Sort dictionary first by key, then by value

I want to double sort a dictionary that might have int or tuple as keys.

d = {33:1, 44:1, (0,5):1  12:2, (1,2):2}

I want it sorted first by its values and secondly by its keys (if possible, not if one is tuple, and second is int).

can anyone help me with this?

Thanks in advance

Upvotes: 2

Views: 1975

Answers (4)

RGS
RGS

Reputation: 981

First of all, you should note that you may not sort a dictionary. You may get a list with keys/values sorted, but never the dictionary itself. You may find in the pydocs that

It is best to think of a dictionary as an unordered set of key: value pairs

Then, you may want to get a sorted list of keys:

# the .keys() returns a list with all the keys, and sorted() sorts them
#sorted_keys = sorted(d.keys()) this does not work since int's and tuples aren't of the same tipe

You can try this:

d_tuples = []
d_int = []
sorted_keys = []
for key in d.keys():
    # type() checks the variable type
    if type(key) == int:
        d_int.append(key)
    elif type(key) == tuple:
        d_tuples.append(key)
sorted_keys = d_tuples + sorted(d_int)

Or the sorted list of values:

sorted_values = sorted(d.values())

Upvotes: 0

volcano
volcano

Reputation: 3582

Or just

sorted(d.items(), key=lambda v: v[::-1])

EDIT: Since OP requires the result as a dictionary

OrderedDict(sorted(d.items(), key=lambda v: v[::-1]))

Upvotes: 4

alvas
alvas

Reputation: 122042

>>> d = {33:1, 44:1, (0,5):1, 12:2, (1,2):2}
>>> {k:v for k,v in sorted(d.items(), key=lambda v: v[::-1])}
{(1, 2): 2, 33: 1, 44: 1, (0, 5): 1, 12: 2}
>>> from collections import OrderedDict
>>> OrderedDict({k:v for k,v in sorted(d.items(), key=lambda v: v[::-1])})
OrderedDict([((1, 2), 2), (33, 1), (44, 1), ((0, 5), 1), (12, 2)])
>>> sorted(d.items(), key=lambda v: v[::-1])
[(33, 1), (44, 1), ((0, 5), 1), (12, 2), ((1, 2), 2)]

Upvotes: 1

mshsayem
mshsayem

Reputation: 18008

How about this?

>>> d = {33:1, 44:1, (0,5):1, 12:2, (1,2):2}
>>> helper_dict = {}
>>> for k,v in d.items():
        helper_dict.setdefault(v,[]).append(k)    

>>> sorted_items = [(k,i) for k in sorted(helper_dict.keys()) for i in sorted(helper_dict[k]) ]
>>> sorted_items
[(1, 33), (1, 44), (1, (0, 5)), (2, 12), (2, (1, 2))]

Upvotes: 0

Related Questions