python字典中的操作

字典的查找方式:
通过键去查找
例1. dic1 = {‘name’:‘ligang’,‘age’:16} 【查值】
   print(dic1[‘name’])
结果:ligang
例2. dic1 = {‘name’:‘ligang’,‘age’:16}
   print(list(dic1.values())) 【查所有的值】
结果:[‘ligang’, 16]
例3. dic1 = {‘name’:‘ligang’,‘age’:16}
   print(list(dic1.keys())) 【查所有的键】
结果:[‘name’, ‘age’]
例4. dic1 = {‘name’:‘ligang’,‘age’:16}
   print(list(dic1.items())) 【查所有的键和值】
结果:[(‘name’, ‘ligang’), (‘age’, 16)]

例1. dic1 = {‘name’:‘ligang’,‘age’:16}
   dic1[‘name’] = ‘lihua’ 【把将要改的值用键找出,重新赋值】
   print(dic1)
结果:{‘name’: ‘lihua’, ‘age’: 16}
例2. 【 update 函数就是将dic2更新到dic1中原来有的直接覆盖,没有的直接添加】
   dic1 = {‘name’:‘ligang’,‘age’:16}
   dic2 = {‘1’:‘1111’,‘name’:‘xiao’,‘2’:‘3333’}
   dic1.update(dic2)
   print(dic1)
   print(dic2)
结果:{‘name’: ‘xiao’, ‘age’: 16, ‘1’: ‘1111’, ‘2’: ‘3333’}
{‘1’: ‘1111’, ‘name’: ‘xiao’, ‘2’: ‘3333’}

例1. dic1 = {‘name’:‘ligang’,‘age’:12,‘hobby’:‘girl’}
   del dic1[‘age’] 【del 方法就是删除字典中指定的键值对,或者删除整个字典】
   print(dic1)
结果:{‘name’: ‘ligang’, ‘hobby’: ‘girl’}
clear 函数就是删除这个字典的所有内容,但是该字典还是存在
例2. dic1 = {‘name’:‘ligang’,‘age’:12,‘hobby’:‘girl’}
   print(dic1.pop(‘age’))
   print(dic1)
【pop 函数的用法与列表中的用法相似,用在字典中就是删除其对应的键值对,并且得出返回值】
结果 {‘name’: ‘ligang’, ‘hobby’: ‘girl’}
例3. dic1 = {‘name’:‘ligang’,‘age’:12,‘hobby’:‘girl’}
   a = dic1.popitem()
   print(a)
   print(dic1)
【 popitem 函数就是随机删除字典中的某一个键值对,并且以元组的形式返回】
结果:(‘hobby’, ‘girl’)
{‘name’: ‘ligang’, ‘age’: 12}
其他对字典的操作方法
增加:
例1. dic1 = dict.fromkeys([‘host1’,‘host2’,‘host3’],[‘test1’,‘teat2’])
   print(dic1)
结果:{‘host1’: [‘test1’, ‘teat2’], ‘host2’: [‘test1’, ‘teat2’], ‘host3’: [‘test1’, ‘teat2’]}
例2. dic1 = dict.fromkeys([‘host1’,‘host2’,‘host3’],[‘test1’])
   print(dic1)
结果:{‘host1’: [‘test1’], ‘host2’: [‘test1’], ‘host3’: [‘test1’]}
例3. dic1 = dict.fromkeys([‘host1’,‘host2’,‘host3’],‘test1’)
   print(dic1)
结果:{‘host1’: ‘test1’, ‘host2’: ‘test1’, ‘host3’: ‘test1’}
修改
例1. dic1 = dict.fromkeys([‘host1’,‘host2’,‘host3’],[‘test1’,‘tesr2’])
   dic1[‘host1’][1] = ‘test7’ 【多级字典的嵌套的修改方式就是这样的】
   print(dic1)
结果:{‘host1’: [‘test1’, ‘test7’], ‘host2’: [‘test1’, ‘test7’], ‘host3’: [‘test1’, ‘test7’]
例2.
排序
例1. dic1 = {6:‘666’,10:‘333’,2:‘444’}
   print(sorted(dic1)) 【引用sorted()函数就是对字典中的键按编码排序】
结果:[2, 6, 10]
例2. dic1 = {6:‘666’,10:‘333’,2:‘444’}
   print(sorted(dic1.items()))
【此处使用了items 表示对字典中的键进行排序,同时输出键值对】
【items 表示键值对】
结果:[(2, ‘444’), (6, ‘666’), (10, ‘333’)]
例3. dic1 = {6:‘666’,10:‘333’,2:‘444’}
   print(sorted(dic1.values()))【在字典后面加上values 表示对值进行排序】
结果:[‘333’, ‘444’, ‘666’]
字典的遍历
例1. dic1 = {‘name’:‘lihau’,‘age’:12,‘hobby’:‘girl’}
   for i in dic1:
   print(i,dic1[i])
结果:name lihau
age 12
hobby girl
例2. dic1 = {‘name’:‘lihau’,‘age’:12,‘hobby’:‘girl’}
   for i in dic1.items():
   print(i)
结果:(‘name’, ‘lihau’)
(‘age’, 12)
(‘hobby’, ‘girl’)
例3. dic1 = {‘name’:‘lihau’,‘age’:12,‘hobby’:‘girl’}
   for i,v in dic1.items():
   print(i,v)
结果:name lihau
age 12
hobby girl

猜你喜欢

转载自blog.csdn.net/IT_creator/article/details/89531633
今日推荐