想以排序方式查看字典合并

Abh*_*han 1 python python-3.x

我能够合并两个字典,但想与dict1一起继续看dict 2

def Merge(dict1, dict2):
    res={**dict1, **dict2}

    return res

dict1= {'a':3,'b':7,'c':9}
dict2= {'d':7,'e':8}
mergedict = Merge(dict1,dict2)

print(mergedict)
Run Code Online (Sandbox Code Playgroud)

实际结果{'d': 7, 'a': 3, 'e': 8, 'b': 7, 'c': 9}

预期结果{'a':3, 'b':7, 'c':9, 'd':7, 'e':8}

Sun*_*tha 7

dict仅保留python 3.7的插入顺序。对于旧版本的python使用OrderedDict

在Python 3.7及更高版本上

>>> {**dict1,**dict2}
{'a': 3, 'b': 7, 'c': 9, 'd': 7, 'e': 8}
Run Code Online (Sandbox Code Playgroud)

对于旧版本

>>> from collections import OrderedDict
>>> dict1 = OrderedDict(sorted({'a':3,'b':7,'c':9}.items()))
>>> dict2 = OrderedDict(sorted({'d':7,'e':8}.items()))      
>>> OrderedDict(dict1,**dict2)
OrderedDict([('a', 3), ('b', 7), ('c', 9), ('d', 7), ('e', 8)])
Run Code Online (Sandbox Code Playgroud)