标签:列表 items python学习 item clear val 结果 col ems
1 dic1 = {‘name‘:‘paoche‘, 2 ‘age‘:19, 3 ‘active‘:[‘beijing‘,‘hebei‘], 4 ‘id‘:{‘wangyi‘:‘skmdod008b‘, 5 ‘sina‘:‘skmdod00bc‘ 6 } 7 }
1 dic1[‘high‘] = 180 #没有键值对,则追加 2 dic1[‘age‘] = 30 #有键值,则修改 3 print(dic1) 4 """ 5 结果为: 6 {‘name‘: ‘paoche‘, ‘age‘: 19, ‘active‘: [‘beijing‘, ‘hebei‘], ‘id‘: {‘wangyi‘: ‘skmdod008b‘, ‘sina‘: ‘skmdod00bc‘}} 7 {‘name‘: ‘paoche‘, ‘age‘: 30, ‘active‘: [‘beijing‘, ‘hebei‘], ‘id‘: {‘wangyi‘: ‘skmdod008b‘, ‘sina‘: ‘skmdod00bc‘}, ‘high‘: 180} 8 """
1 dic1.setdefault(‘weight‘,185) #没有键值对,则追加 2 dic1.setdefault(‘name‘,‘xiaobai‘) #有键值,则不做任何操作 3 print(dic1) 4 """ 5 结果为: 6 {‘name‘: ‘paoche‘, ‘age‘: 19, ‘active‘: [‘beijing‘, ‘hebei‘], ‘id‘: {‘wangyi‘: ‘skmdod008b‘, ‘sina‘: ‘skmdod00bc‘}, ‘weight‘: 185} 7 """
1 print(dic1.pop(‘id‘)) #按键删除,返回被删除的键值对中的值,没有对应的键则报错 2 print(dic1.pop(‘id‘,None)) #按键删除,若没有该键,则返回指定的值,一般返回None,也可以是任意内容 3 print(dic1) 4 """ 5 结果为: 6 {‘wangyi‘: ‘skmdod008b‘, ‘sina‘: ‘skmdod00bc‘} 7 None 8 {‘name‘: ‘paoche‘, ‘age‘: 19, ‘active‘: [‘beijing‘, ‘hebei‘]} 9 """
1 print(dic1.popitem()) #随机删除,返回被删键值组成的元组 2 """ 3 结果为: 4 (‘id‘, {‘wangyi‘: ‘skmdod008b‘, ‘sina‘: ‘skmdod00bc‘}) 5 """
1 print(dic1.clear()) #返回None 2 print(dic1) 3 """ 4 结果为: 5 None 6 {} 7 """
1 del dic1[‘id‘] 2 print(dic1) 3 del dic1 4 """ 5 结果为: 6 {‘name‘: ‘paoche‘, ‘age‘: 19, ‘active‘: [‘beijing‘, ‘hebei‘]} 7 """
1 dic1[‘age‘] = 30
1 dic2 = { 2 ‘name‘:‘paoche‘, 3 ‘age‘:19 4 } 5 dic3 = { 6 ‘age‘:30, 7 ‘weight‘:180 8 } 9 dic2.update(dic3) #将dic3中的数据更新dic2,有则修改,没有则新加 10 print(dic2) 11 """ 12 结果为: 13 {‘name‘: ‘paoche‘, ‘age‘: 30, ‘weight‘: 180} 14 """
1 print(dic1[‘age‘]) 2 ‘‘‘ 3 结果为: 4 19 5 ‘‘‘
1 print(dic1.get(‘age‘)) 2 print(dic1.get(‘age1‘)) 3 print(dic1.get(‘age1‘,‘没有对应的键‘)) 4 ‘‘‘ 5 结果为: 6 19 7 None 8 没有对应的键 9 ‘‘‘
1 print(dic1.keys()) 2 ‘‘‘ 3 结果为: 4 dict_keys([‘name‘, ‘age‘, ‘active‘, ‘id‘]) 5 ‘‘‘
1 print(dic1.values()) 2 ‘‘‘ 3 结果为: 4 dict_values([‘paoche‘, 19, [‘beijing‘, ‘hebei‘], {‘wangyi‘: ‘skmdod008b‘, ‘sina‘: ‘skmdod00bc‘}]) 5 ‘‘‘
1 print(dic1.items()) 2 ‘‘‘ 3 结果为: 4 dict_items([(‘name‘, ‘paoche‘), (‘age‘, 19), (‘active‘, [‘beijing‘, ‘hebei‘]), (‘id‘, {‘wangyi‘: ‘skmdod008b‘, ‘sina‘: ‘skmdod00bc‘})]) 5 ‘‘‘
items()取出的列表可以直接赋值给变量使用
1 for k,v in dic1.items(): 2 print(k,v) 3 ‘‘‘ 4 结果为: 5 name paoche 6 age 19 7 active [‘beijing‘, ‘hebei‘] 8 id {‘wangyi‘: ‘skmdod008b‘, ‘sina‘: ‘skmdod00bc‘} 9 ‘‘‘
标签:列表 items python学习 item clear val 结果 col ems
原文地址:https://www.cnblogs.com/ershoupaoche/p/9505770.html