【问题标题】:How to sort this dicts by keys?如何按键排序这个字典?
【发布时间】:2019-08-12 11:22:34
【问题描述】:

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

我需要实现一个算法来排序。

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

我知道如果我合并它们,它们会被排序,但我需要为我做这件事。

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])

【问题讨论】:

  • 你有不同类型的元素。你如何比较这些?例如([1], "wer")?
  • @CristiFati elif not isinstance(first_dict[key], type(second_dict[key])):,无论如何我需要比较密钥,比如 a>b>c 等等。

标签: python sorting dictionary key


【解决方案1】:

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

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

(2) Python 中的字典是未排序的数据结构。它们无法排序。我建议您不要使用字典并切换到(key, value) 元组列表。另一种选择是使用库collections 中的OrderedDict 数据结构。更多信息在这里: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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-27
    • 2011-06-17
    • 2021-04-24
    • 2016-08-31
    • 2015-10-10
    • 2012-07-30
    相关资源
    最近更新 更多