Python学习笔记_字典

字典

{‘key1’:‘value1’,‘key2’:‘value2’, … ,‘keyN’:‘valueN’}
 注1:引号、冒号、大括号,逗号隔开;
 注2:字典是无序、可变的,保存的内容是以“键-值对”的形式存储的;
 注3:键是唯一的,而值可以有多个。

1.字典的创建和删除

(1)通过映射函数创建字典dictionary = dict(zip(list1,list2))
注:dict( )函数;zip( )函数,用于多个列表或元组对应位置的元素组合为元组
(2)通过给定的“键-值对”创建字典dictionary = dict(key1 = 'value1', key2 = 'value2', key3 = 'value3')
注:dict( )函数;等号;键无引号,值有引号
(3)创建空字典dictionary = { } 或 dictionary = dict( )
(4)创建值为空的字典dictionary = dict.fromkeys(name)
注:无引号,错误写法:dict.fromkeys('name')
#(1)通过映射函数创建字典
Pinyin = ('che','chen','chi')
Hanzi = ['车','陈','吃']
dictionary = dict(zip(Pinyin,Hanzi)) #输出:{'che': '车', 'chen': '陈', 'chi': '吃'}
print(dictionary)

#(2)通过给定的键-值对创建字典
dictionary = dict(che='车',chen='陈',chi='吃')
print(dictionary) #输出:{'che': '车', 'chen': '陈', 'chi': '吃'}

2.访问字典

dictionary = {'che':'车','chen':'陈','chi':'吃'}
(1)直接使用print( )函数print(dictionary)
(2)通过键值对访问字典dictionary['key1']
注:中括号[ ],引号
dictionary.get('key1', 'default')
注:引号;default为自定义的默认值,当指定键不存在时,得到的结果就是所指定的默认值
dictionary = {'che':'车','chen':'陈','chi':'吃'}
print(dictionary)#输出:{'che': '车', 'chen': '陈', 'chi': '吃'}
print(dictionary['che'])#输出:车
print('读音是cheng的汉字有:',dictionary.get('cheng','字典里没有这个读音')) #输出:读音是cheng的汉字有: 字典里没有这个读音

3.遍历字典

dictionary = {'che':'车','chen':'陈','chi':'吃'}
(1)for item in dictionary.items( ):
    print(item)
items( )函数
(2)for key, value in dictionary.items( ):
    print(key,value)
items( )函数
(3)for key in dictionary.keys( ):
    print(key)
keys( )函数
(2)for value in dictionary.values( ):
    print(value)
values( )函数
dictionary = {'che':'车','chen':'陈','chi':'吃'}
for item in dictionary.items( ):
    print(item)
#输出:
('che', '车')
('chen', '陈')
('chi', '吃')
for key, value in dictionary.items( ):
    print(key,value)
#输出:
che 车
chen 陈
chi 吃
for key in dictionary.keys( ):
    print(key)
#输出:
che
chen
chi
for value in dictionary.values( ):
    print(value)
#输出:
车
陈
吃

4.添加、修改和删除字典元素

(1)添加、修改元组元素dictionary['key'] = 'value'
注1:中括号、引号
注2:如果字典中有键“key”,则为修改;如果字典中无键“key”,则为添加
(2)删除字典元素del dictionary['key']
注1:中括号、引号
注2:先判断,后删除
   if 'key1' in dictionary:
     del dictionary['key1']

5.字典推导式

{键表达式 : 值表达式 for循环}
注:大括号、冒号
a = ['姓名','性别','学号','班级'] #作为键的列表
b = ['小红','女','1234','机械1班'] #作为值的列表
dictionary = {i:j for i,j in zip(a,b)}
print(dictionary)
#输出:{'姓名': '小红', '性别': '女', '学号': '1234', '班级': '机械1班'}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

木子Dilwyn

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

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

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

打赏作者

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

抵扣说明:

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

余额充值