温馨提示×

python字典合并与排序的方法是什么

小亿
98
2023-11-23 14:08:19
栏目: 编程语言

在Python中,可以使用update()函数来合并两个字典。该函数将一个字典的键值对添加到另一个字典中。如果有相同的键,则会更新该键的值。

例如:

dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
dict1.update(dict2)
print(dict1)  # 输出: {'a': 1, 'b': 2, 'c': 3, 'd': 4}

如果要对字典按照键或值进行排序,可以使用sorted()函数结合lambda表达式来实现。

按照键排序:

dict1 = {'b': 2, 'a': 1, 'd': 4, 'c': 3}
sorted_dict = dict(sorted(dict1.items(), key=lambda x: x[0]))
print(sorted_dict)  # 输出: {'a': 1, 'b': 2, 'c': 3, 'd': 4}

按照值排序:

dict1 = {'b': 2, 'a': 1, 'd': 4, 'c': 3}
sorted_dict = dict(sorted(dict1.items(), key=lambda x: x[1]))
print(sorted_dict)  # 输出: {'a': 1, 'b': 2, 'c': 3, 'd': 4}

以上代码中,sorted()函数将字典的items()转化为可迭代对象,并使用lambda表达式指定排序的依据,最后通过dict()函数将排序后的结果转化为字典。

0