Python之第六章 内置容器 --- 字典(映射)

目录

Python之第六章 内置容器 --- 字典(映射)

1.定义:

2.格式:

3.字典创建示例

​4.增加字典元素

5.删除字典

6.字典的访问

7.字典的复制

8.使用get()方法获取指定的键值

9.字典的遍历

10.字典内涵列表

11.字典内含字典


Python之第六章 内置容器 --- 字典(映射)

1.定义:

        字典属于可变序列,使用‘ 键:值 ’(key - value)的方式配对存储数据。Python的字典由”键”和“值“构成,其中”键“表示查找的数据,”值“表示查找的结构,类似于新华字典的“ 拼音 - 汉字”

2.格式:

        dictname = { ' key1 ' : ' value1 ',' key2 ' : ' value2 ', ... , ' key n ' : ' value n ', }

dictname --- 字典名

key --- 元素的键

value --- 元素的值,可为任意数据,不需要唯一

3.字典创建示例

dict1 = {'andy': 1001, 'fox': 1002, 'alice': 1003}
dict2 = {}  # 空字典
dict3 = dict()  # 使用dict()方法,强制转换 创建空字典
​
name = ['lose', '凝光', '风霜', '学业']
sign = ['001', '002', '110', '561']
# 使用zip()函数 将列表或元组对应的元素组合成字典
dict4 = dict(zip(name, sign))
​
dict5 = dict(a=92.5, b=77.4, c=64.9)  # 键 = 值的方式创建
print(dict1, '\n', dict2, '\n', dict3, '\n', dict4, '\n', dict5)
​
结果:
{'andy': 1001, 'fox': 1002, 'alice': 1003} 
 {} 
 {} 
 {'lose': '001', '凝光': '002', '风霜': '110', '学业': '561'} 
 {'a': 92.5, 'b': 77.4, 'c': 64.9}
​
Process finished with exit code 0

​4.增加字典元素

        格式 --- dictname[键] = 值

        

dict1 = {'西瓜': 1, '香蕉': 8, "苹果": 10}
print(dict1)
dict1['橘子'] = 6
print(dict1)
dict1["苹果"] = 12
print(dict1)
​
结果:
{'西瓜': 1, '香蕉': 8, '苹果': 10}
{'西瓜': 1, '香蕉': 8, '苹果': 10, '橘子': 6}
{'西瓜': 1, '香蕉': 8, '苹果': 12, '橘子': 6}
​
Process finished with exit code 0

5.删除字典

        del 字典名[键] --- 删除字典中特定元素

dictname.clear( ) --- 清空字典全部元素

del 字典名 --- 删除字典整体

        例

dict1 = {'西瓜': 1, '香蕉': 8, "苹果": 10}
del dict1['西瓜']
print(dict1)
dict1.clear()
print(dict1)
del dict1
print(dict1)
​
结果:
{'香蕉': 8, '苹果': 10}
{}
Traceback (most recent call last):
  File "E:\pythontext\test3.py", line 1886, in <module>
    print(dict1)
NameError: name 'dict1' is not defined
​
Process finished with exit code 1
​

6.字典的访问

        dictname [ ]

        

dict1 = {'西瓜': 1, '香蕉': 8, "苹果": 10}
print(dict1['香蕉'], dict1['苹果'])
​
结果:
8 10
​

7.字典的复制

        作用 --- 保护原字典内容

        格式 --- new_dictname = dictname.copy( )

        

dict1 = {'西瓜': 1, '香蕉': 8, "苹果": 10}
dict2 = dict1.copy()
print(dict1, '\n', dict2)
print(id(dict1), id(dict2)) # 字典拷贝 默认使用深拷贝
​
结果:
{'西瓜': 1, '香蕉': 8, '苹果': 10} 
 {'西瓜': 1, '香蕉': 8, '苹果': 10}
1597252597504 1597252597696
​
Process finished with exit code 0
​

注意:

        默认为深拷贝,新字典地址独立

8.使用get()方法获取指定的键值

        格式 --- dictname.get( key, default )

key --- 指定的键

defaul --- 可省略,用于指定键不存在时,返回默认值,若省略则返回None

dict1 = {'Name': 'andy', 'Age': 17, 'Class': 19}
print(dict1.get('Age'))
print(dict1.get("Score"))
print(dict1.get('Score', '无此选项'))
# 若访问的键不存在则执行default
​
结果:
17
None
无此选项

9.字典的遍历

        格式1 --- 遍历值,items()方法

for i in dictname.items():

        处理 i

        格式2 --- 键:值遍历

for key,value indictname.items():

        处理 key 和 value

name = ['lose', '凝光', '风霜', '学业']
sign = ['001', '002', '110', '561']
dict1 = dict(zip(name, sign))
​
for i in dict1.items():
    print(i)
​
for j, k in dict1.items():
    print(j, "的编号为:", k)
​
结果:
('lose', '001')
('凝光', '002')
('风霜', '110')
('学业', '561')
lose 的编号为: 001
凝光 的编号为: 002
风霜 的编号为: 110
学业 的编号为: 561
​
Process finished with exit code 0

​        格式3 --- 遍历字典的键,keys()

for key dictname.keys():

        处理

players = {'张三':77.5,'李四':55.9,"王五":87.6}
for name in players.keys():
    print("姓名:",name)
    
结果:
姓名: 张三
姓名: 李四
姓名: 王五
​
Process finished with exit code 0

注意:

        1. 不允许同一个键出现2次,创建时如果同一个键被赋值2次,后一个会被记住

dict1 = {'andy': 1001, "score": 92, 'andy': 1002}
print(dict1)
​
结果:
{'andy': 1002, 'score': 92}

        2. 键必须不可变,所以使用数字、字符串、元组来充当,列表不行

dict1 = {['andy']: 1001, "score": 92}
print(dict1)
​
结果:
Traceback (most recent call last):
File "E:\pythontext\test3.py", line 1916, in <module>
 dict1 = {['andy']: 1001, "score": 92}
TypeError: unhashable type: 'list'
​
Process finished with exit code 1

10.字典内涵列表

        列表存储在字典中时,一般作为字典的某个键的值出现,需要使用嵌套循环完成处理,外层循环用来取得字典的键,内存循环用于取得值或将列表拆解

        例

sports = {'andy': ['篮球', '足球', '橄榄球'],
          'jenny': ['体操', '游泳'],
          'joker': ['羽毛球', '轮滑鞋', '骑车']}
for name,na_sport in sports.items():
    print('%s喜欢的运动是:'%name,end=' ')
    for sp in na_sport:
        print(' ',sp,end=' ')
    print()
    
结果:
andy喜欢的运动是:   篮球   足球   橄榄球 
jenny喜欢的运动是:   体操   游泳 
joker喜欢的运动是:   羽毛球   轮滑鞋   骑车 
​
Process finished with exit code 0

11.字典内含字典

        字典存储在字典中一般用于表示字典中键的值

wechat = {'001': {'last_name': '张三', 'first_name': '李四', 'city': '西安'},
          '002': {'last_name': '王五', 'first_name': '刘柳', 'city': '咸阳'}}
for num, name in wechat.items():
    print("账号:", num, end=' ')
    print('姓名:', name['first_name'], end=' ')
    print('住址:', name['city'])
    
结果:
账号: 001 姓名: 李四 住址: 西安
账号: 002 姓名: 刘柳 住址: 咸阳
​
Process finished with exit code 0

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

White乄joker

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值