python之字典,,字典(diction
python之字典,,字典(diction
字典(dictionary):字典的定义使用{},大括号,每个值用“,”隔开,key和value使用“:”分隔。
dict1 = {‘tom‘: [12, ‘Amercia‘], ‘jerry‘: [11, ‘Amercia‘] ,‘jack‘: [20, ‘England‘]}
字典的特性:
字典是无序的,因为它没有下标,用key来当索引,所以是无序的
字典的key必须是唯一的,因为它是通过key来进行索引的,所以key不能重复,天生就去重
字典的一些操作
增加元素
1 dict1 = {‘tom‘: [12, ‘Amercia‘], ‘jerry‘: [11, ‘Amercia‘] ,‘jack‘: [20, ‘England‘]}2 3 dict1[‘rose‘] = [21, ‘England‘]
修改元素
dict1 = {‘tom‘: [12, ‘Amercia‘], ‘jerry‘: [11, ‘Amercia‘] ,‘jack‘: [20, ‘England‘]}dict1[‘tom‘] = [14, ‘Amercia‘]
删除元素
1 dict1 = {‘tom‘: [12, ‘Amercia‘], ‘jerry‘: [11, ‘Amercia‘] ,‘jack‘: [20, ‘England‘]}2 dict1.pop(‘jerry‘) #删除指定元素3 del dict1(‘jerry‘) #使用del方法删除
查询元素
1 dict1 = {‘tom‘: [12, ‘Amercia‘], ‘jerry‘: [11, ‘Amercia‘] ,‘jack‘: [20, ‘England‘]}2 3 print(dict1.get(‘jack‘)) #这种方式如果key不存在的话,会返回None4 5 print(dict[‘jack‘]) #这种方式如果key不存在的话,会报错6 7 print(‘jack‘ in dict1) #判断jack是否在这个字典中,返回True或者False
内置方法
1 dict1 = {‘tom‘: [12, ‘Amercia‘], ‘jerry‘: [11, ‘Amercia‘] ,‘jack‘: [20, ‘England‘]} 2 3 print(dict1.keys()) #打印所有key 4 5 print(dict1.values()) #打印所有value 6 7 print(dict1.setdefault.(‘judy‘,[20,‘England‘])) #如果key存在,不动,不存在,添加 8 9 dict2 = {‘john‘: [24, ‘russia‘]}10 11 dict1.update(dict2) #更新字典,如果key存在,更新;不存在,添加
12 print(dict1.items()) #转变成列表
python之字典
相关内容
- python_面向对象——对象之间的关联关系,,1.将类中的对
- 用Python Matplotlib 制作动画,,前言本文的文字及图片
- Python文件操作大全,,Python 编程文
- 我与Python的相爱相杀-类与对象,,面向对象(oop):
- Python基础教程总结(二),, 上周总结了一下P
- (转)LINUX CENTOS7下安装PYTHON,,LINUX CENT
- python如何监控PostgreSQL代码运行,,如何监控Postgr
- python实现24点游戏(地球上最短的24点游戏代码?),
- 程序媛计划——python网络编程,,class1 正则表
- 用python做时间序列预测六:相关函数图、偏相关函数图
评论关闭