首页 > 解决方案 > 如何按键排序这个字典?

问题描述

我正在尝试按它们的键对这两个字典进行排序,我该怎么做?

我需要实现一个算法来对此进行排序。

我尝试了一些排序算法,但没有奏效。

我知道如果我合并它们,它们将被排序,但我需要一些东西来为我做这件事。

FIRST_DICT = {'x': [1, 2, 3],
                  'y': 1,
                  'z': set([1, 2, 3]),
                  'w': 'qweqwe',
                  't': {'a': [1, 2]},
                  'm': [1],
                  'q': 'xzz'}
SECOND_DICT = {'x': [4, 5, 6],
                   'y': 4,
                   'z': set([4, 2, 3]),
                   'w': 'asdf',
                   't': {'a': [3, 2]},
                   'm': "wer",
                   'n': 'x'}
NEW_DICT = {}

我还需要将排序后的键放入这个合并函数中:

def merge(first_dict, second_dict, new_dict):
    """This will merge the two dictionfirst_dictries"""
    unique = True
    keys_in_both_lists = conc(first_dict, second_dict, unique)s
    for key in keys_in_both_lists:
        if first_dict.get(key) is None:
            new_dict[key] = second_dict.get(key)
            print "Not found:", key
        elif second_dict.get(key) is None:
            new_dict[key] = first_dict.get(key)
            print "Not found:", key
        elif not isinstance(first_dict[key], type(second_dict[key])):
            new_dict[key] = (first_dict[key], {second_dict[key]})
        elif isinstance(first_dict[key], list):
            new_dict[key] = conc(first_dict[key],
                                 second_dict[key],
                                 unique=False)
        elif isinstance(first_dict[key], set):
            new_dict[key] = first_dict[key] | second_dict[key]
        elif isinstance(first_dict[key], dict):
            new_dict[key] = merge(first_dict[key],
                                  second_dict[key],
                                  {})
        else:
            new_dict[key] = first_dict[key] + second_dict[key]
    return new_dict

我期望这个:

'm': ([1], "wer")}, 'n': 'x', 'q': 'xzz','t': {'a': [1, 2, 3, 2]}, 'w': 'qweqweasdf', 'x': [1,2,3,4,5,6], 'y': 5, 'z': set([1,2,3,4])

标签: pythonsortingdictionarykey

解决方案


这里有两个不同的问题:(1)如何连接两个字典和(2)如何对字典进行排序。

(1) 加入字典的操作可以直接使用itertools.groupby模块进行(看下面的代码)。关于 itertools groupby 的更多信息:https ://docs.python.org/2/library/itertools.html#itertools.groupby

(2) Python 中的字典是未排序的数据结构。它们无法排序。我建议您不要使用字典并切换到(key, value)元组列表。另一种选择是使用OrderedDict库中的数据结构collections。更多信息在这里:https ://docs.python.org/2/library/collections.html#collections.OrderedDict

我解决问题的方法:

d1 = {'x': [1, 2, 3],
                  'y': 1,
                  'z': set([1, 2, 3]),
                  'w': 'qweqwe',
                  't': {'a': [1, 2]},
                  'm': [1],
                  'q': 'xzz'}
d2 = {'x': [4, 5, 6],
                   'y': 4,
                   'z': set([4, 2, 3]),
                   'w': 'asdf',
                   't': {'a': [3, 2]},
                   'm': "wer",
                   'n': 'x'}


from itertools import groupby        
from collections import OrderedDict

elements = list(d1.items()) + list(d2.items())
elements = sorted(elements, key=lambda x:x[0])
groups = groupby(elements, key=lambda x:x[0])
dict_reduced = []
for k, g in groups:
   dict_reduced.append((k, [x[1] for x in g]))

dict_reduced = OrderedDict(dict_reduced)

推荐阅读