Python字典大总结
字典定义及特点
字典是键值对的无序集合。
字典中的每个元素包含用冒号分隔开的“ 键 ”和“ 值 ”两部分,表示一种映射关系,也称为关联数组。
字典中可以包含任意数量的键值对,字典的键值对之间没有顺序,并且不能重复!
字典的创建及访问
方法一:直接使用花括号 {} 创建字典
方法二:用 dict() 函数创建字典,不过用这种方法创建时会使用很多圆括号,这是因为 dict() 的参数可以是一个序列,但不能是多个序列。
dic = {1:'A', 2:'B', 3:'C'}
dic
>>>{1: 'A', 2: 'B', 3: 'C'}
dict((('A',101),('B',201),('C',41)))
>>>{'A': 101, 'B': 201, 'C': 41}
dict(('A',101),('B',201),('C',41))
>>>TypeError Traceback (most recent call last)
<ipython-input-4-386d7957efc7> in <module>
----> 1 dict(('A',101),('B',201),('C',41))
TypeError: dict expected at most 1 arguments, got 3
需要注意:
1.同一个键不得出现两次。创建字典时,如果同一个键被赋值了两次,则后一个值被记住。
2.键必须不可变。可以用数字、字符串或者元组作为键,但是列表不行(列表是可变的)。
访问字典的某个值:
可以直接利用键值对关系索引元素,格式为“ dict [ key ] ”,注意不能像列表和字符串那样用索引来查找字典中的元素!!
dict_a = {1:'A', 2:'B', 3:'C'}
dict_b = {'A': 101, 'B': 201, 'C': 41}
print(dict_a[2])
print(dict_b['C'])
>>>B
41
字典的内建函数
| 代码 | 描述 |
|---|---|
| len(dict) | 计算字典元素的个数,即键的总数 |
| str(dict) | 以字符串形式输出字典 |
字典的内建方法
| 代码 | 描述 |
|---|---|
| dict.get(key,default) | 返回指定键的值,如果值不在字典中,则返回default值 |
| dict.items() | 以列表返回可遍历的(键,值)元组数组,注意是 dict_items 类型的,如果希望是列表类型的可以采用 list(dict.items()) |
| dict.keys() | 返回所有键的信息,注意是 dict_keys 类型的 |
| dict.values() | 返回所有值的信息,注意是 dict_values 类型的 |
| dict.pop(key,default) | 键存在则返回相应值,同时删除键值对,否则返回默认值 |
| dict.popitem() | 随机从字典中取出一个键值对,以元组 (key, value) 形式返回,同时将该键值对从字典中删除 |
| dict.clear() | 删除所有键值对,清空字典 |
| dict.copy() | 返回一个具有相同键值对的新字典,不是原字典的副本 |
| dict.update(dict2) | 把 dict2 的键值对更新到 dict 中,无返回值(如果是键相同,值不同,则只保留最新的值) |
| dict.setdefault(key, default = None) | 键存在则返回相应值,键不存在则添加键并将值设为默认值 |
举例说明:
d={'age':18}
print(d.get('name','Eric'))
print(d.get('age',20))
>>>Eric
18
dict_1 = {'a':1, 'b':3, 'c':5}
dict_2 = {'d':7}
dict_1.update(dict_2)
dict_1
>>>{'a': 1, 'b': 3, 'c': 5, 'd': 7}
dict_3 = {'b':33}
dict_1.update(dict_3)
dict_1
>>>{'a': 1, 'b': 33, 'c': 5, 'd': 7}
dict_4 = {'a':1, 'b':3, 'c':5}
dict_4.setdefault('d',99)
>>>99
dict_4
>>>{'a': 1, 'b': 3, 'c': 5, 'd': 99}
str(dict_4)
>>>"{'a': 1, 'b': 3, 'c': 5}"
len(dict_4)
>>>3
get() 方法的妙用:
在统计某字符在一段文本中出现的次数时,字典的 get 方法非常实用!!
txt = "苹果 芒果 草莓 芒果 苹果 草莓 芒果 香蕉 芒果 草莓"
lis = txt.split(' ')
d = {}
for i in lis:
d[i] = d.get(i,0) + 1
print(d)
>>>{'苹果': 2, '芒果': 4, '草莓': 3, '香蕉': 1}
更新字典(添加、修改)
字典是一种动态结构,可随时在其中修改和添加键值对。
键值对的排列顺序和添加顺序不同!Python 不关心键值对的添加顺序,只关心键和值之间的关联关系。
dict_1 = {'a':1, 'b':3, 'c':5}
dict_1['a'] = 11 # 更新 a
dict_1['d'] = 7 # 添加 d
dict_1
>>>{'a': 11, 'b': 3, 'c': 5, 'd': 7}
字典的删除
使用 del 语句既能删除字典中的单一元素,也能删除整个字典。
使用方法 dict.clear() 可以将整个字典清空。
dict_1 = {'a':1, 'b':3, 'c':5}
del dict_1['a'] # 删除键'a'
dict_1
>>>{'b': 3, 'c': 5}
dict_1.clear() # 清空字典
dict_1
>>>{}
del dict_1 # 删除整个字典
dict_1
>>>NameError Traceback (most recent call last)
<ipython-input-16-e44350bd6891> in <module>
----> 1 del dict_1
2 dict_1
NameError: name 'dict_1' is not defined
遍历字典
遍历所有键值对
user={
'username':'efermi',
'first':'enrico',
'last':'fermi',
}
print(user.items())
输出结果:
dict_items([(‘username’, ‘efermi’), (‘first’, ‘enrico’), (‘last’, ‘fermi’)])
for key,value in user.items():
print(f"\nKey: {key}")
print(f"Value: {value}")
输出结果:
Key: username
Value: efermi
Key: first
Value: enrico
Key: last
Value: fermi
遍历所有的键
favorite_languages={
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python',
}
for name in favorite_languages.keys():
print(name.title())
输出结果:
Jen
Sarah
Edward
Phil
注意:遍历字典时,会默认遍历所有的键!!!使用for name in favorite_languages.keys()和for name in favorite_languages结果是一样的!
按特定顺序遍历字典中的所有键
for name in sorted(favorite_languages.keys()):
print(f"{name.title()},thank you for taking the poll!")
输出结果:
Edward,thank you for taking the poll!
Jen,thank you for taking the poll!
Phil,thank you for taking the poll!
Sarah,thank you for taking the poll!
遍历所有的值
print("the following language have been mentioned:")
for language in favorite_languages.values():
print(language)
输出结果:
the following language have been mentioned:
python
c
ruby
python
print("the following language have been mentioned:")
for language in set(favorite_languages.values()): #利用set去重
print('\t',language)
输出结果:
the following language have been mentioned:
ruby
c
python
注意:
如果遍历字典时 没有说明 遍历 键 或者 值 或者 都要 时,只给出了字典名称,那么遍历的是字典的键!!
嵌套
嵌套:
将一系列字典存储在列表中,或者将列表作为值储存在字典中,这称为嵌套。
字典列表
aliens=[]
for alien_number in range(30):
new_alien={'color':'green','points':5,'speed':'slow'}
aliens.append(new_alien)
for i in aliens[:5]:
print(i)
print('...')
print(f'外星人总数为:{len(aliens)}')
输出结果:
{‘color’: ‘green’, ‘points’: 5, ‘speed’: ‘slow’}
{‘color’: ‘green’, ‘points’: 5, ‘speed’: ‘slow’}
{‘color’: ‘green’, ‘points’: 5, ‘speed’: ‘slow’}
{‘color’: ‘green’, ‘points’: 5, ‘speed’: ‘slow’}
{‘color’: ‘green’, ‘points’: 5, ‘speed’: ‘slow’}
…
外星人总数为:30
for alien in aliens[:3]:
if alien['color']=='green':
alien['color']='yellow'
alien['points']=10
alien['speed']='medium'
for i in aliens[:5]:
print(i)
print('...')
输出结果:
{‘color’: ‘yellow’, ‘points’: 10, ‘speed’: ‘medium’}
{‘color’: ‘yellow’, ‘points’: 10, ‘speed’: ‘medium’}
{‘color’: ‘yellow’, ‘points’: 10, ‘speed’: ‘medium’}
{‘color’: ‘green’, ‘points’: 5, ‘speed’: ‘slow’}
{‘color’: ‘green’, ‘points’: 5, ‘speed’: ‘slow’}
…
在字典中存储列表
例1:
pizza={
'crust':'thick',
'toppings':['mushrooms','extra cheese'],
}
print(f"You ordered a {pizza['crust']}-crust pizza with the following toppings:")
for topping in pizza['toppings']:
print('\t'+topping)
输出结果:
You ordered a thick-crust pizza with the following toppings:
mushrooms
extra cheese
例2:
favorite_languages={
'jen':['python','ruby'],
'sarah':['c'],
'edward':['ruby','go'],
'phil':['python'],
}
for name,languages in favorite_languages.items():
if len(languages)!=1:
print(f"\n{name.title()}'s favorite languages are:")
for language in languages:
print('\t',language.title())
elif len(languages)==1:
print(f"\n{name.title()}'s favorite language is:")
print('\t',languages[0].title())
输出结果:
Jen's favorite languages are:
Python
Ruby
Sarah's favorite language is:
C
Edward's favorite languages are:
Ruby
Go
Phil's favorite language is:
Python
在字典中存储字典
users={
'aeinstein':{
'first':'albert',
'last':'einstein',
'location':'princeton',
},
'mcurie':{
'first':'matie',
'last':'curie',
'location':'paris',
},
}
for username,user_info in users.items():
print(f"\nUsername:{username}")
print(f"\tFull name:{user_info['last'].title()} {user_info['first'].title()}")
print(f"\tLocation:{user_info['location'].title()}")
输出结果:
Username:aeinstein
Full name:Einstein Albert
Location:Princeton
Username:mcurie
Full name:Curie Matie
Location:Paris
本文详细介绍了Python字典的定义、创建与访问方法、内建函数和方法、更新操作、遍历方式以及字典的嵌套使用。字典是无序的键值对集合,键必须是不可变类型。通过get()方法、del语句和clear()函数可实现字典的修改和删除。同时,展示了如何遍历字典的所有键值对、键和值,并演示了字典列表和字典中存储列表、字典的例子。
1766

被折叠的 条评论
为什么被折叠?



