您的位置:首页 > 娱乐 > 明星 > python字典操作

python字典操作

2024/10/6 0:26:37 来源:https://blog.csdn.net/vah101/article/details/142258655  浏览:    关键词:python字典操作

1. 字典的初始化

创建空的字典:

test_dict={}

或:

test_dict=dict()

使用初始值:

test_dict = {"one":1,"two":2,"three":3}

键必须是唯一的,但值则不必

2. 查找一个key值是否在字典中:

key = "test"
test_dict = {"one":1,"two":2,"three":3}

方法1:

if key in test_dict:print(str(key) + " is in dict ")

方法2:

value = test_dict.get(key)
if value is not None:print(f"The key '{key}'")

3. 给字典中增加键值对

test_dict["four"] = 4
#或
#和get()类似, 但如果键不已经存在于字典中,将会添加键并将值设为default。
test_dict.setdefault(key, default=None)

4. 遍历字典读取键值对

方法1:

for key in test_dict:value = test_dict[key]print(key, value)

方法2:

for key, value in test_dict.items():print(key, value)

方法3:

for key in test_dict.keys():value = test_dict[key]print(key, value)

方法4:

for value in test_dict.values():print(value)

5. 删除字典中指定的key

key = "test"

方法1:

if key in test_dict:del test_dict[key] 

方法2:

if key in test_dict:test_dict.pop(key)

删除字典中最后一个元素:

test_dict.popitem()

popitem 方法用于随机删除字典中的一项(键值对),并以元组形式返回被删除的键值对。由于字典是无序的,实际上是删除最后一项。


6. 统计字典的元素个数(key的数量)

len(test_dict)

7. 将字典以字符串形式输出:

print(str(test_dict))	

8. 清除字典中的元素

test_dict.clear()

9. 删除整个字典

del(test_dict)

删除之后test_dict就不存在了

10. 根据给定的key返回value

print(test_dict["three"])

test_dict.get("three", default=None)

返回指定键的值,如果值不在字典中返回default值

11. 字典排序:

test_dict = {"one":1,"two":2,"three":3}

根据value升序排序:

sorted_items = sorted(test_dict.items(), key=lambda item: item[1])

根据value降序排序:

sorted_items = sorted(test_dict.items(), key=lambda item: item[1], reverse = True)

根据key升序排序:

sorted_items = sorted(test_dict.keys())   #只有key

根据key降序排序:

sorted_items = sorted(test_dict.items(), key=lambda item: item[0], reverse = True) 

12. 将字典转换为list

test_dict = {"one":1,"two":2,"three":3}score_list = list(test_dict.items())

结果为:[('one', 1), ('two', 2), ('three', 3)]
 

只要key:

score_list = list(test_dict.keys())

结果为:['one', 'two', 'three']
 

只要value:

score_list = list(test_dict.values())

结果为:[1, 2, 3]

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com