通过名称来访问各个值的数据结构,这种数据结构称为映射。
字典是python中唯一的映射类型。
一、创建字典
phone = {‘xiaoming‘:‘123‘,‘jack‘:‘3232131132‘}
dict_1 = {} #空字典
二、函数dict
d = dict(name = ‘jack‘,age = 33)
返回
>>d {‘age‘:33,‘name‘:‘jack‘}
三、字典的方法
1)clear
定义:清除
函数:dict.clear()
代码:
1 dic = {"name":"solo",‘age‘:20,‘hobby‘:‘bastkball‘} 2 d = dic.clear() 3 print(d)
打印结果:
1 None
2)copy
定义:copy一个字典,并返回一个新字典,其包含的键值对与原来的字典相同。
函数:dict.copy()
代码:
1 dic = {"name":"solo",‘age‘:20,‘hobby‘:‘bastkball‘} 2 d = dic.copy() 3 print(d) 4 print(dic)
结果:
{‘name‘: ‘solo‘, ‘age‘: 20, ‘hobby‘: ‘bastkball‘} {‘name‘: ‘solo‘, ‘age‘: 20, ‘hobby‘: ‘bastkball‘}
修改copy后的新字典,不会改变原字典的值(浅复制)
替换时,原件不受影响,但是修改副本的值,原件也会跟着改变
代码:
1 dic = {"name":"solo",‘age‘:20,‘hobby‘:‘bastkball‘} 2 d = dic.copy() 3 d[‘name‘] = ‘jack‘ 4 print(d) 5 print(dic)
结果:
1 {‘name‘: ‘jack‘, ‘age‘: 20, ‘hobby‘: ‘bastkball‘} 2 {‘name‘: ‘solo‘, ‘age‘: 20, ‘hobby‘: ‘bastkball‘}
3)fromkeys
定义:方法fromkeys创建一个新字典,其中包含指定的键,且每个键对应的值都是None
函数:dict.fromkeys([‘key‘,‘key‘])
代码:
1 d = dict.fromkeys([‘name‘,‘age‘]) 2 print(d)
结果:
1 {‘name‘: None, ‘age‘: None}
如果不使用默认值None,也可以指定值
函数:
dict.fromkeys([key,key],‘value‘)
代码:
1 d = dict.fromkeys([‘name‘,‘age‘],‘unknow‘) 2 print(d)
结果:
1 {‘name‘: ‘unknow‘, ‘age‘: ‘unknow‘}
原文地址:https://www.cnblogs.com/aszeno/p/10226917.html
时间: 2024-10-14 10:44:07