python dictionary values sorting

后端 未结 4 1994
没有蜡笔的小新
没有蜡笔的小新 2020-12-16 21:31

I have 2 dictionaries, dict1 and dict2 which contain the same keys, but different values for the keys. What I want to do is for each dictionary, s

4条回答
  •  醉梦人生
    2020-12-16 21:45

    A simple solution for small dicts is

    dict1 = {"a":0.6, "b":0.3, "c":0.9, "d":1.2, "e":0.2}
    dict2 = {"a":1.4, "b":7.7, "c":9.0, "d":2.5, "e":2.0}
    k1 = sorted(dict1, key=dict1.get)
    k2 = sorted(dict2, key=dict2.get)
    diffs = dict((k, k2.index(k) - k1.index(k)) for k in dict1)
    

    A more efficient, less readable version for larger dicts:

    ranks1 = dict(map(reversed, enumerate(sorted(dict1, key=dict1.get))))
    ranks2 = dict(map(reversed, enumerate(sorted(dict2, key=dict2.get))))
    diffs = dict((k, ranks2[k] - ranks1[k]) for k in dict1)
    

提交回复
热议问题