Sorting dict using sorted() in python

sorted(iterable, key, reverse)

http://pythoncentral.io/how-to-sort-python-dictionaries-by-key-or-value/

http://stackoverflow.com/questions/613183/sort-a-python-dictionary-by-value

month = {“one”: “January”, “two”: “February”, “three”: “March”}

list(month)

sort dict kesy: sorted(month)

sort dict values: sorted(month.values())

sort dict keys using dict values:  sorted(month, key=month.__getitem__)

sort the values in month by its keys: [value for key, value in sorted(month.items())]

 

sort a dict by value:

dict(sorted(month.items(),  key=operator.itemgetter(1)))

sort a dict by value:

dict(sorted(month.items(),  key=operator.itemgetter(0)))

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s