python-demo/basic/字典.py

37 lines
875 B
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@File : 字典.py
@Author : lichao
@Date : 2024/12/6 11:17
@Software : PyCharm
"""
dict_data = {"name": "test", "age": 18, "address": "beijing"}
# 直接对字典进行遍历获得是字典的key
for key in dict_data:
print(key)
# 元组拆包
for key, value in dict_data.items():
print(key, value)
# 获取字典数据,如果访问不存在的key会报错
print(dict_data["name"])
# 使用get方法如果访问不存在的key不会报错返回None,第二个参数用来设置默认值(建议使用)
# print(dict_data["height"])
print(dict_data.get("height", 180))
dict_data["name"] = "test1"
dict_data["gender"] = "man"
print(dict_data)
# 删除字典中的元素
del dict_data["age"]
# 清空字典
dict_data.clear()
# 空字典声明
dict_data1 = {}
dict_data2 = dict()