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

29次阅读
没有评论

共计 834 个字符,预计需要花费 3 分钟才能阅读完成。

在 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() 函数将排序后的结果转化为字典。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-13发表,共计834字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)