python基础学习5----字典

2021-07-17 04:05

阅读:477

标签:values   name   删除   方法   括号   ict   返回   bsp   改变   

字典由大括号和键值对组成,特点为无序,键唯一

1.字典的创建

#直接创建字典
dic1={‘name‘:‘a‘,‘age‘:20}
#通过dict创建字典,输出都为{‘name‘: ‘a‘, ‘age‘: 20} dic2=dict(((‘name‘,‘a‘),(‘age‘,20))) print(dic2) dic3=dict([[‘name‘,‘a‘],[‘age‘,20]]) print(dic3)

2.字典的增加与修改

dic1={‘name‘:‘a‘}
dic1[‘age‘]=20
print(dic1)
#如果字典中存在age,那么将age的值修改为20,如果不存在,则添加‘age‘:20

age=dic1.setdefault(‘age‘,18)
print(age)
#键存在,不改动,返回字典中相应的键对应的值,输出为20

hobby=dic1.setdefault(‘hobby‘,‘sport‘)
print(hobby)
#键不存在,在字典中中增加新的键值对,并返回相应的值,输出为sport

3.字典的查询,通过键去查找

dic3={‘age‘: 20, ‘name‘: ‘a‘, ‘hobby‘: ‘sport}

print(dic3[‘name‘])#输出a

print(dic3.keys())#输出dict_keys([‘age‘, ‘name‘, ‘hobby‘]),其他同理
print(list(dic3.keys()))#输出[‘age‘, ‘name‘, ‘hobby‘]
print(list(dic3.values()))#输出[20, ‘a‘, ‘sport‘]
print(list(dic3.items()))#输出[(‘age‘, 20), (‘name‘, ‘a‘), (‘hobby‘, ‘sport‘)]

#更新字典
dic4={‘age‘: 20, ‘name‘: ‘a‘, ‘hobby‘:‘sport‘}
dic5={‘1‘:‘111‘,‘name‘:‘222‘}
dic4.update(dic5)
print(dic4)#输出{‘age‘: 20, ‘name‘: ‘222‘, ‘hobby‘: ‘sport‘, ‘1‘: ‘111‘}
print(dic5)#输出{‘1‘: ‘111‘, ‘name‘: ‘222‘}

4.字典的删除

dic5 = {‘name‘: ‘a‘, ‘age‘: 20, ‘hobby‘: sport}

dic5.clear() # 清空字典

del dic5[‘name‘] #删除字典中指定键值对

print(dic5.pop(‘age‘)) #删除字典中指定键值对,并返回该键值对的值,应该输出20

a = dic5.popitem() #随机删除某组键值对,并以元组方式返回值

del dic5  #删除整个字典

5.其他创建字典的方法

dic6=dict.fromkeys([‘host1‘,‘host2‘,‘host3‘],‘test‘)
print(dic6)#输出{‘host3‘: ‘test‘, ‘host1‘: ‘test‘, ‘host2‘: ‘test‘}

dic6=dict.fromkeys([‘host1‘,‘host2‘,‘host3‘],[‘test1‘,‘tets2‘])
print(dic6)#{‘host2‘: [‘test1‘, ‘tets2‘], ‘host3‘: [‘test1‘, ‘tets2‘], ‘host1‘: [‘test1‘, ‘tets2‘]}

dic6[‘host2‘][1]=‘test3‘
print(dic6)
#{‘host3‘: [‘test1‘, ‘test3‘], ‘host2‘: [‘test1‘, ‘test3‘], ‘host1‘: [‘test1‘, ‘test3‘]},这里不仅仅只改变了host2的值

6.字典的遍历

可以利用for循环 

dic5 = {‘name‘: ‘a‘, ‘age‘: 20, ‘hobby‘: ‘sport‘}

 for i in dic5:
     print(i,dic5[i])

 for i,v in dic5.items():
     print(i,v)

  

 

python基础学习5----字典

标签:values   name   删除   方法   括号   ict   返回   bsp   改变   

原文地址:https://www.cnblogs.com/sfencs-hcy/p/9532612.html


评论


亲,登录后才可以留言!