标签:python
一、字典
python中的字典不是序列,而是一种映射;不通过位置而是通过键存储。字典是可变的。
1、字典的映射操作
使用{}定义字典,以key:value形式存储数据,在字典中key是唯一的 >>> one_dict = {‘name‘:"jym",‘age‘:23,‘addr‘:‘xinjiang‘} #通过key查找数据 >>> one_dict[‘name‘] ‘jym #修改 >>> one_dict[‘name‘] = "Jym" >>> print(one_dict) {‘name‘: ‘Jym‘, ‘age‘: 23, ‘addr‘: ‘xinjiang‘} >>> one_dict[‘age‘] += 1 >>> print(one_dict) {‘name‘: ‘Jym‘, ‘age‘: 24, ‘addr‘: ‘xinjiang‘} #添加,直接赋值不在字典中的键,会创建该键值 >>> one_dict[‘job‘] = "ops" >>> print(one_dict) {‘name‘: ‘Jym‘, ‘age‘: 24, ‘addr‘: ‘xinjiang‘, ‘job‘: ‘ops‘} #字典的嵌套 >>> two_dict = {‘name‘:{‘first‘:"jy",‘last‘:"meng"},‘age‘:32,‘addr‘:[‘sh‘,‘xj‘]} >>> two_dict[‘name‘][‘first‘] ‘jy‘ >>> two_dict[‘addr‘][0] ‘sh‘
2、字典的方法
#清空字典 >>> two_dict.clear() >>> print(two_dict) {} #删除方法一 >>> two_dict = {‘name‘:{‘first‘:"jy",‘last‘:"meng"},‘age‘:32,‘addr‘:[‘sh‘,‘xj‘]} >>> two_dict[‘name‘].pop(‘first‘) ‘jy‘ >>> print(two_dict) {‘name‘: {‘last‘: ‘meng‘}, ‘age‘: 32, ‘addr‘: [‘sh‘, ‘xj‘]} #删除方法二 >>> del two_dict[‘name‘][‘last‘] >>> print(two_dict) {‘name‘: {}, ‘age‘: 32, ‘addr‘: [‘sh‘, ‘xj‘]} #获取字典中value >>> get_dict = two_dict.get(‘age‘) >>> print(get_dict) 32 #通过一个字典更新另一个字典,如果两个字典键值相同,那么以要被更新的字典为准 >>> two_dict.update(one_dict) >>> print(two_dict) {‘name‘: ‘Jym‘, ‘age‘: 24, ‘addr‘: ‘xinjiang‘, ‘job‘: ‘ops‘} #将字典转变为列表(少用) >>> print(two_dict) {‘name‘: ‘Jym‘, ‘age‘: 24, ‘addr‘: ‘xinjiang‘, ‘job‘: ‘ops‘} >>> print(two_dict.items()) dict_items([(‘name‘, ‘Jym‘), (‘age‘, 24), (‘addr‘, ‘xinjiang‘), (‘job‘, ‘ops‘)]) #取字典的values值 >>> print(two_dict.values()) dict_values([‘Jym‘, 24, ‘xinjiang‘, ‘ops‘]) #取字典的keys值 >>> print(two_dict.keys()) dict_keys([‘name‘, ‘age‘, ‘addr‘, ‘job‘]) #判断key值是否在字典中 >>> ‘name‘ in two_dict True #取一个key值,如果存在,即取出,如果不存在,就在字典中加入该kv值 >>> print(two_dict.setdefault(‘name‘)) Jym >>> print(two_dict.setdefault(‘name1‘,"newkv")) newkv >>> print(two_dict) {‘name‘: ‘Jym‘, ‘age‘: 24, ‘addr‘: ‘xinjiang‘, ‘job‘: ‘ops‘, ‘name1‘: ‘newkv‘} #给定列表,将列表中的值取出作为key生成字典 >>> print(dict.fromkeys([1,2,3,4],‘newvalue‘)) {1: ‘newvalue‘, 2: ‘newvalue‘, 3: ‘newvalue‘, 4: ‘newvalue‘} #随机删除字典中的kv值(慎用) >>> two_dict.popitem() (‘name1‘, ‘newkv‘) >>> print(two_dict) {‘name‘: ‘Jym‘, ‘age‘: 24, ‘addr‘: ‘xinjiang‘, ‘job‘: ‘ops‘} >>> two_dict.popitem() (‘job‘, ‘ops‘) >>> print(two_dict) {‘name‘: ‘Jym‘, ‘age‘: 24, ‘addr‘: ‘xinjiang‘}
3、字典排序
第一种方法 #将字典的key值取出换为列表存储 sort_list = list(id_db.keys()) #使用列表的方法排序 sort_list.sort() #按照顺序打印字典 for key in sort_list: print(key,id_db[key]) 结果: C:\Python36\python36.exe C:/Users/Administrator/PycharmProjects/cto3/day2/dictionary.py 659001199601105413 {‘name‘: ‘jonny‘, ‘age‘: 18, ‘addr‘: ‘xj‘} 659001199701105413 {‘name‘: ‘david‘, ‘age‘: 17, ‘addr‘: ‘sh‘} 659001199801105413 {‘name‘: ‘george‘, ‘age‘: 16, ‘addr‘: ‘gz‘} 第二种方法 for key in sorted(id_db): print(key,id_db[key])
本文出自 “linux启航” 博客,请务必保留此出处http://jiayimeng.blog.51cto.com/10604001/1898498
标签:python
原文地址:http://jiayimeng.blog.51cto.com/10604001/1898498