首页 > 编程知识 正文

Python输出字典的方法整理

时间:2023-11-20 23:15:46 阅读:291963 作者:WDKQ

本文将从多个方面介绍Python输出字典的方法,涵盖了字典的创建、遍历、排序等内容,具体操作请看下文。

一、字典的创建

Python中创建字典的方式有两种,一种是使用花括号 {},另一种是使用 dict() 函数。具体如下:

dict1 = {'apple': 1, 'banana': 2, 'pear': 3}
dict2 = dict(apple=1, banana=2, pear=3)
print(dict1) # {'apple': 1, 'banana': 2, 'pear': 3}
print(dict2) # {'apple': 1, 'banana': 2, 'pear': 3}

可以看到,两种方法创建的字典是一样的。

二、字典的遍历

Python遍历字典有三种方式,分别是遍历键、遍历值、遍历键值对。具体如下:

1、遍历键

dict1 = {'apple': 1, 'banana': 2, 'pear': 3}
for key in dict1:
    print(key) # apple banana pear

可以看到,使用 for 循环遍历字典时,默认是遍历字典的键。

2、遍历值

dict1 = {'apple': 1, 'banana': 2, 'pear': 3}
for value in dict1.values():
    print(value) # 1 2 3

可以看到,使用 values() 函数可以遍历字典的值。

3、遍历键值对

dict1 = {'apple': 1, 'banana': 2, 'pear': 3}
for key, value in dict1.items():
    print(key, value) # apple 1, banana 2,pear 3

可以看到,使用 items() 函数可以同时遍历字典的键和值。

三、字典的排序

Python中字典的排序需要使用 sorted() 函数,其中可以加入 lambda 表达式等操作实现对字典的排序。

1、按键排序

dict1 = {'apple': 1, 'banana': 2, 'pear': 3}
dict2 = dict(sorted(dict1.items(), key=lambda x: x[0]))
print(dict2) # {'apple': 1, 'banana': 2, 'pear': 3}

可以看到,使用 key=lambda x: x[0] 可以对字典按照键进行排序。

2、按值排序

dict1 = {'apple': 1, 'banana': 2, 'pear': 3}
dict2 = dict(sorted(dict1.items(), key=lambda x: x[1]))
print(dict2) # {'apple': 1, 'banana': 2, 'pear': 3}

可以看到,使用 key=lambda x: x[1] 可以对字典按照值进行排序。

3、按值反向排序

dict1 = {'apple': 1, 'banana': 2, 'pear': 3}
dict2 = dict(sorted(dict1.items(), key=lambda x: x[1], reverse=True))
print(dict2) # {'pear': 3, 'banana': 2, 'apple': 1}

可以看到,使用 key=lambda x: x[1], reverse=True 可以对字典按照值进行反向排序。

四、字典的复制

Python中字典的复制有两种方式,一种是浅拷贝,另一种是深拷贝。

1、浅拷贝

dict1 = {'apple': 1, 'banana': 2, 'pear': 3}
dict2 = dict1.copy()
print(dict2) # {'apple': 1, 'banana': 2, 'pear': 3}

可以看到,使用 copy() 函数可以实现字典的浅拷贝。

2、深拷贝

import copy
dict1 = {'apple': [1, 2, 3], 'banana': 2, 'pear': 3}
dict2 = copy.deepcopy(dict1)
dict2['apple'].append(4)
print(dict1) # {'apple': [1, 2, 3], 'banana': 2, 'pear': 3}
print(dict2) # {'apple': [1, 2, 3, 4], 'banana': 2, 'pear': 3}

可以看到,使用 deepcopy() 函数可以实现字典的深拷贝。

五、字典的删除

Python中删除字典的方式有两种,分别是 del 关键字和 pop() 函数。

1、使用 del

dict1 = {'apple': 1, 'banana': 2, 'pear': 3}
del dict1['apple']
print(dict1) # {'banana': 2, 'pear': 3}

可以看到,使用 del 关键字可以删除字典中的键值对。

2、使用 pop()

dict1 = {'apple': 1, 'banana': 2, 'pear': 3}
dict1.pop('apple')
print(dict1) # {'banana': 2, 'pear': 3}

可以看到,使用 pop() 函数可以删除字典中的键值对,并且可以返回删除的值。

结语

本文从字典的创建、遍历、排序、复制、删除等多个方面介绍了Python输出字典的方法,同时给出了对应示例代码。希望对大家有所帮助。

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。