Python学习第三天之字典

柳三千

文章最后更新时间:2025年06月13日

前言:

Python中的字典是一种键值对映射结构,通过“键(Key)”可快速查找对应“值(Value)”,类似“哈希”“映射”概念,实现数据的高效关联查询。

创建字典

# 创建空字典
emptyDict = dict()
emptyDict2 = {}
print("Length:", len(emptyDict))
print("Length:", len(emptyDict2))

查看字典的值

# 基础字典
dict1 = {'ip': '192.168.23.12', 'host': 'web', 'port': 80, 'version': '19,0'}
print(dict1)
print(dict1['host'])

# 字典嵌套
dev = {
    'r1': {
        'vendor': 'Cisco',
        'model': '4451',
        'ip': '192.168.11.51'
    },
    'sw1': {
        'vendor': 'Huawei',
        'model': 'S5700',
        'ip': '192.168.11.151'
    }
}
print(dev['r1']['vendor'])
print(dev['r1']['ip'])

# 格式化打印(pprint)
from pprint import pprint
dict1 = {'Vendor': 'HUAWEI', 'Model': 'Quidway S5328C-EI', 'Ports': 24, 'Version': 'VRP (R) Software, Version 5.150 (V200R005C00SPC500)'}
print(dict1)  # 普通打印
pprint(dict1)  # 格式化打印

新增字典的值

student = {'小米': 86, "张三": 69, "许刚不许刚": 59}
print(student)

student['小明'] = 99
student['小红'] = '99'
print(student)

更改字典的值

student['小红'] = 96
print(student)

清空与删除字典值

student = {'小米': 86, "张三": 69, "许刚不许刚": 59}
print(student)

student.clear()  # 清空字典
print(student)

# 删除指定键值
del student['小米']
print(student)

拷贝字典

直接赋值(浅拷贝)

'''
直接赋值相当于多个标签指向同一对象,修改其中一个会影响另一个
'''
student = {'小米': 86, "张三": 69, "许刚不许刚": 59}
student2 = student
print(student2)

# id值相同
print(id(student))
print(id(student2))

# 修改其中一个字典,另一个同步变化
student['李四'] = 29
print(student)
print(student2)

copy()方法(浅拷贝)

student = {'小米': 86, "张三": 69, "许刚不许刚": 59}
student2 = student.copy()
print(student2)

# id值不同
print(id(student))
print(id(student2))

# 修改其中一个字典,另一个不受影响
student['李四'] = 29
print(student)
print(student2)

嵌套字典的浅拷贝问题

student = {'小米': 86, "张三": 69, "许刚不许刚": [66, 38, 29]}
student2 = student.copy()
print(student2)

# id值不同
print(id(student))
print(id(student2))

# 修改嵌套列表中的值,两个字典同步变化
student['许刚不许刚'][1] = 99
print(student)
print(student2)

# 列表元素的id相同,说明浅拷贝未复制嵌套对象
print(id(student['许刚不许刚'][1]))
print(id(student2['许刚不许刚'][1]))

索引方法:get()、setdefault()

get():安全获取值

student = {'小米': 86, "张三": 69, "许刚不许刚": [66, 38, 29]}
student2 = student.copy()
print(student2['刘霸天'])  # 报错:KeyError: '刘霸天'

print(student2.get('刘霸天'))  # 返回值:None

setdefault():获取或新增值

student = {'小米': 86, "张三": 69, "许刚不许刚": [66, 38, 29]}
print(student.setdefault('小米'))  # 返回已有值:86

print(student.setdefault('刘霸天'))  # 返回None,并新增键值对
print(student.setdefault('刘小二', '998'))  # 返回指定默认值:998
print(student)

字典返回值方法

dev = {'vendor': 'Huawei', 'model': 'S5700', 'ip': '192.168.11.151', 'version': None, 'local': 'shantou'}
print(dev.keys())    # 返回所有键:dict_keys(['vendor', 'model', 'ip', 'version', 'local'])
print(dev.values())  # 返回所有值:dict_values(['Huawei', 'S5700', '192.168.11.151', None, 'shantou'])
print(dev.items())   # 返回所有键值对:dict_items([('vendor', 'Huawei'), ('model', 'S5700'), ...])

dict.fromkeys:创建字典模板

# 创建空模板(值为None)
sw1_keys = ['vendor', 'model', 'local', 'ports']
sw1 = dict.fromkeys(sw1_keys)
print(sw1)  # {'vendor': None, 'model': None, 'local': None, 'ports': None}

# 创建带默认值的模板
from pprint import pprint
sw1 = dict.fromkeys(sw1_keys, 'wgsy_none')
pprint(sw1)  # {'local': 'wgsy_none', 'model': 'wgsy_none', 'ports': 'wgsy_none', 'vendor': 'wgsy_none'}

字典生成式

items = ['Fruits', 'Books', 'Others']
prices = [98, 76, 89]
lst = zip(items, prices)  # 打包为元组列表:[('Fruits', 98), ('Books', 76), ('Others', 89)]
d = {item: price for item, price in lst}
print(d)  # {'Fruits': 98, 'Books': 76, 'Others': 89}
文章版权声明:除非注明,否则均为柳三千运维录原创文章,转载或复制请以超链接形式并注明出处。

取消
微信二维码
微信二维码
支付宝二维码