python dictionary values sorting

后端 未结 4 2018
没有蜡笔的小新
没有蜡笔的小新 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:40

    A dictionary is not the right data structure to solve this problem. You should convert to sorted lists as soon as possible and produce the dictionary only as the final result. The following sample solution uses iterators and generator expressions where possible, to avoid creating too many (potentially large) helper lists along the way:

    def get_ranking(vals):
        '''Return a list of pairs: (key, ranking), sorted by key.'''
        ranking = sorted(((v, k) for k, v in vals.iteritems()), reverse=True)
        return sorted((k, i) for (i, (_v, k)) in enumerate(ranking))
    
    def ranking_diff(rank1, rank2):
        return dict((k, v1 - v2) for (k, v1), (_, v2) in itertools.izip(rank1, rank2))
    
    def get_diffs(dict1, dict2):
        r1 = get_ranking(dict1)
        r2 = get_ranking(dict2)
        return ranking_diff(r1, r2)
    
    print get_diffs(dict1, dict2)
    # prints: {'a': -2, 'c': 1, 'b': 2, 'e': 1, 'd': -2}
    

    Please note that this solution assumes that both dicts contain exactly the same keys.

提交回复
热议问题