Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting dictionary keys in python [duplicate]

Tags:

python

sorting

People also ask

Can a Python dictionary have duplicate keys?

The straight answer is NO. You can not have duplicate keys in a dictionary in Python.

Does dictionary accept duplicate keys?

The Key value of a Dictionary is unique and doesn't let you add a duplicate key entry. To accomplish the need of duplicates keys, i used a List of type KeyValuePair<> .

Can dictionary have multiple same keys?

No, each key in a dictionary should be unique. You can't have two keys with the same value. Attempting to use the same key again will just overwrite the previous value stored. If a key needs to store multiple values, then the value associated with the key should be a list or another dictionary.


I like this one:

sorted(d, key=d.get)

>>> mydict = {'a':1,'b':3,'c':2}
>>> sorted(mydict, key=lambda key: mydict[key])
['a', 'c', 'b']

my_list = sorted(dict.items(), key=lambda x: x[1])

[v[0] for v in sorted(foo.items(), key=lambda(k,v): (v,k))]