字典是以键值对存储的数据类型,形如:{‘name‘: ‘小明‘}。在低版本中无顺序,在3.6以上版本有顺序。
字典的key必须是不可变数据类型(如字符串,数字),value可以是任意类型。
#定义并输出一个字典 dic={ ‘name‘:‘小明‘, ‘age‘:20, ‘height‘:180, ‘sex‘:‘male‘ } print(dic)
dic={ ‘name‘:‘小明‘, ‘age‘:20, ‘sex‘:‘male‘ } dic[‘height‘]=180 #weight元素不存在,创建新的元素 dic.setdefault("weight",123) #调用setdefault方法增加元素 print(dic)
dic={ ‘name‘:‘小明‘, ‘age‘:20, ‘sex‘:‘male‘, "weight":123, 1:2 } dic.pop(‘name‘,None) dic.popitem() del dic[‘weight‘] # dic.clear() # del dic print(dic)
dic1={ ‘name‘:‘小明‘, ‘age‘:20, ‘sex‘:‘male‘, "weight":123, 1:2 } dic2={‘name‘:‘小明‘,‘height‘:180} dic1.update(dic2) print(dic1)
dic={ ‘name‘:‘小明‘, ‘age‘:20, ‘sex‘:‘male‘, "weight":123, 1:2 } print(dic.keys()) print(dic.values()) print(dic.items())
用for循环遍历字典得到的是键
dic={ ‘name‘:‘小明‘, ‘age‘:20, ‘sex‘:‘male‘, "weight":123, 1:2 } for i in dic: print(i)
原文:https://www.cnblogs.com/north-sea/p/11306047.html