#Python-Sort dictionary by value/key

Dictionary doesn't have an order, list has order. So, first, turn dictionary into a list of tuples. [(key1: value1), (key2, value2)....]

dic.items()
then sort

import operator dic = {k1:6, k2:2, k3:4, k4:3} sorted.val.dic = sorted(dic.items(), key = operator.itemgetter(1)) #sorted by value sorted.key.dic = sorted(dic.items(), key = operator.itemgetter(0)) #sorted by keys

你可能感兴趣的:(#Python-Sort dictionary by value/key)