37 lines
875 B
Python
37 lines
875 B
Python
#!/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()
|