python:數據類型dict

1、字典

key -->value 儲存大量數據,並且是關係型數據,查詢速度很是快

  數據類型分類:

    可變數據類型:list , dict, setpython

    不可變的數據類型:int , bool, str, tupleapp

    字典的鍵:不可變數據類型spa

    字典的值:任意數據類型指針

 

   hash哈希

    可變數據類型(不可哈希):list , dict,setcode

    不可變數據類型(可哈希):int , bool, str ,tupleblog

  增

    第一種 有則覆蓋,沒有就添加

dic = {"name":"jin",
       "age":18,
       "sex":"male"
       }
dic['hobby'] = 'girl'
print(dic)
dic['name'] = 'alex'
print(dic)
dic['hobby'] = 'love'
print(dic)

    第二種 setdefault,無則添加,有則不變內存

dic = {"name":"jin",
       "age":18,
       "sex":"male"
       }
dic.setdefault('work')
print(dic)
dic.setdefault('work','ps')
print(dic)
dic.setdefault('name')
print(dic)

  刪

  

  pop有返回值(能夠本身設置返回值) 

dic = {"name":"jin",
       "age":18,
       "sex":"male"
       }
print(dic.pop('age'))
print(dic.pop('name'))
 print(dic.pop('hahah','None'))
print(dic.pop('name','沒有此關鍵值'))#添加返回值爲‘沒有此關鍵字’
沒有設置返回值,而且也沒有該元素,  會報錯 

   clear清空字符串

dic = {"name":"jin",
       "age":18,
       "sex":"male"
       }
 dic.clear()
 print(dic)

   del刪除get

dic = {"name":"jin",
       "age":18,
       "sex":"male"
       }

del dic
del dic['name']
print(dic)
del dic['work']
print(dic)
print(dic.popitem())#隨機刪除一對key--》value
print(dic)

  查

 

dic = {"name":"jin",
       "age":18,
       "sex":"male"
       }

print(dic['name'])
print(dic['work'])#沒有,報錯
print(dic['age'])
#print(dic('hobby1'))

print(dic.get('name'))
print(dic.get('name1','沒有此賤'))#默認返回none,能夠本身設置返回值
print(dic.get('name1'))

  其餘方法 key()    values()  items()hash

print(dic.keys())
print(dic.keys(),type(dic.keys()))
for i in dic.keys():#打印鍵
   print(i)


for i in dic:#打印鍵
   print(i)

  

print(dic.values())
print(dic.values(),type(dic.values))

for i in dic.values():#將鍵值轉化成列表,而後逐個打印
    print(i)

  

 

print(dic.items())


for i in dic.items():#將鍵和值轉化成列表中成對的元祖
       print(i)
for k,v in dic.items():
print (k,v)

  分別賦值

 

 1 a, b = 2,3
 2 print(a,b)
 3 
 4 a,b = (2,3)
 5 print (a,b)
 6 
 7 a,b = [2,3]
 8  print (a,b)
 9 
10 a= 5
11 b = 4
12 
13 a,b = b,a
14 print(a,b)

 

 字典的嵌套

  

dic = {'name_list':['張三','lisi','隔壁王'],
        'dic2':{'name':'太白','age':12}}
# 1 ,給列表追加一個元素:'旺旺'
dic['name_list'].append('汪汪')
print(dic)
# ,2,給列表lisi所有大寫
dic['name_list'][1] = dic['name_list'][1].upper()
print(dic)
# 3,給dic2 對應的字典添加一個鍵值對:hobby:girl.
dic ['dic2']['sex'] = 'girl'
print (dic)

 

 fromkey

對於可變的列表,內存地址指向的是列表,因此列表裏面的內容改變,並不會引發對應值的改變

dic = dict.fromkeys(['barry','alex',],[])

print(dic)#{'barry': [], 'alex': []}

dic['barry'].append(666)

print(dic)#{'barry': [666], 'alex': [666]}

對於字符串,整型,指針直接指向的是元素的地址,因此元素改變,所對應的也會改變

dic = dict.fromkeys(['barry','alex'],66)

print(dic)#{'barry': 66, 'alex': 66}
dic['alex']= 1
print(dic)#{'barry': 66, 'alex': 1}
相關文章
相關標籤/搜索