一、使用格式
字典的每个键值key=>value对用冒号:分割,每对间用逗号,分割,整个字典包括在花括号{}中:
d={'Michael':95, 'Bob':75, 'Tracy':85}
二、键与值
dict中的键key必须是唯一的、不可变的,因为dict需要根据key计算value的存储位置,该算法也被称为哈希算法(Hash),如字符串、数字。但值value则不必,值可以取任何数据类型,既可以是标准的对象,也可以是用户定义的。
一个key只能对应一个value,内部存放的顺序和key放入的顺序是没有关系的。不允许同一个key出现两次,当多次对一个key放入value,后面的值会把前面的值冲掉:
d['Jack']=90
d['Jack']=88 #可以用于更改某个key的取值
当key不存在时,dict会报错。为避免key不存在的错误,可以通过in判断key是否存在;也可以通过dict提供的get()方法,若key不存在则返回None(返回None时Python的交互环境不显示结果)或自己指定的value:
d['Thomas']
'Thomas' in d
d.get('Thomas')
d.get('Thomas', -1)
同一字典中的键可以是不同类型:
tinydict = {'abc':123, 98.6:37}
三、值的访问
字典作为一种和列表类似的可变容器模型,可以存储任意类型对象。但列表只能通过数字获取数据,字典则可以使用任何东西获取:
names=['Michael', 'Bob', 'Tracy']
scores=[95, 75, 85]
#给定一个名字查找对应的成绩,要先在names中找到对应的位置,再从scores取对应成绩
#list越长耗时越长(类似于从第一页翻字典)
d['Michael']
#用dict实现该需求只需要写一个“名字-成绩”的对照表,直接根据名字查成绩
#无论表有多大,该方法查找的速度不会变慢(类似于通过字典的索引表查字)
通过以上比较我们可以看出字典dict的特点:1.查找和插入的速度极快,不会随着key的增加而变慢;但也正因如此,2.需要占用大量的内存,内存浪费多。
而列表list则相反:1.查找和插入的时间随着元素的增加而增加;2.占用空间小,浪费内存很少。
四、删除字典元素
删除一个key用<字典名>.pop(),该key对应的value也会被删除:
d.pop('Bob')
也可以用del语句:
studict = {'Name':'Runoob', 'Age':7, 'Class':'First'}
del studict['Name'] #删除键'Name'
studict.clear() #清空字典
del studict
print("studict['Age']:", studict['Age'])
#执行最后一步会引发异常,因为执行del后字典studict不再存在
五、内置函数
以空字典为例,使用{}创建空字典:
emptydict = {}
print(emptydict)
{}
len(dict)计算字典元素个数,即键的总数:
print("Length:", len(emptydict))
Length: 0
type(variable)返回输入的变量类型,如果变量是字典就返回字典类型:
print(type(emptydict))
<class 'dict'>
str(dict)输出字典,可以打印的字符串表示:
tinydict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
str(tinydict)
Out[16]: "{'Name': 'Runoob', 'Age': 7, 'Class': 'First'}"
一个小练习
来自Datawhale的【PythonThinking】课程:
#creat a mapping of state to abbreviation
states = {
'Oregon':'OR',
'Florida':'FL',
'California':'CA',
'New York':'NY',
'Michigan':'MI'}
#create a basic set of states and some cities in them
cities = {
'CA':'San Francisco',
'MI':'Detroit',
'FL':'Jacksonville'}
#add some more cities
cities['NY'] = 'New York'
cities['OR'] = 'Portland'
#print out some cities
print('-' * 10) #相当于分割线吧,好可爱
print("Michigan's abbreviation is: ", states['Michigan'])
print("Florida's abbreviation is: ", states['Florida'])
#do it by using the state then cities dict
print('-' * 10)
print("Michigan has:", cities[states['Michigan']])
print("Florida has:", cities[states['Florida']])
#print every state abbreviation
print('-' * 10)
for state, abbrev in list(states.items()):
print(f"{state} is abbreviated {abbrev}")
#print every city in state
print('-' * 10)
for abbrev, city in list(cities.items()):
print(f"{abbrev} has the city {city}")
#now do both at the same time
print('-' * 10)
for state, abbrev in list(states.items()):
print(f"{state} state is abbreviated {abbrev}")
print(f"and has city {cities[abbrev]}")
print('-' * 10)
#safely get a abbreviation by state that might not be there
state = states.get('Texas')
if not state:
print("Sorry, no Texas.")
dict.get(key, default=None)返回指定键的值,如果键不在字典中返回default设置的默认值:
#get a city with a default value
city = cities.get('TX', 'Does Not Exist')
print(f"The city for the state 'TX' is: {city}")