【发布时间】: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