python3 字典問題詳解

2021-09-21 17:42:26 字數 1380 閱讀 6724

1.1 定義字典

dict =

1.2 根據鍵值訪問對應元素值

dict[『name』]

1.3 遍歷所有鍵-值對

for k, v in dict.items():

1.4 遍歷所有鍵

for k in dict.keys():

1.5 遍歷所有值

for v in dict.values():

1.6 刪除以』name』為鍵的鍵-值對

del dict[『name』]

1.7 清空字典所有鍵-值對,保留空字典

dict.clear()

1.8 將整個字典從記憶體中抹去(空的殼也沒保留)

del dict

1.9 淺拷貝乙個字典

dict1 = dict.copy()

1.10 將dict2的鍵-值對更新到dict中

dict.update(dict2)

1.11 建立新的字典(dict.fromkeys())

seq = ('name', 'age', '***')

dict = dict.fromkeys(seq)

print ("new dictionary : %s" % str(dict))

dict = dict.fromkeys(seq, [10, 11])

print ("new dictionary : %s" % str(dict))

#輸出為

#new dictionary :

#new dictionary :

1.12 根據key取出value,如果沒有該key,返回none或者指定的其它值

#dict.get(key, default=none)

dict =

print ("value : %s" % dict.get('age'))

print ("value : %s" % dict.get('***', "na"))

#輸出#value : 27

#value : na

#這一波操作後並沒有將鍵為'***'的鍵-值對寫進字典

1.13 與1.12類似,不同之處是將鍵為』***』的鍵-值對寫進字典

dict.setdefault(key, default = none)

1.14 判斷dict是否有鍵k

if k in dict.keys():

python中可雜湊的物件:integers, strings, tuples, immutable sets.

2.1 可將二維字典的兩個維放在乙個元祖中,從而化解為一維字典的問題。

例:dict[『a』][『b』]改寫為dict[(『a』, 『b』)]

python3字典遍歷 python3字典遍歷

python版本 python3.7 info infog.get name 得到字典info中name的值 info.keys 得到字典info中所有的鍵,結果是乙個物件 dict keys name age 需要注意在python2中該操作得到的是乙個列表 遍歷key for temp in i...

python3字典詳解 python3中字典詳解

字典 dict 1.建立字典的幾種方式 class dict kwarg class dict iterable,kwarg 使用上面的方法構建字典 方法1構建字典 a dict one 1,two 2,three 3 a輸出結果 方法2構建字典 a dict a輸出結果 方法3構建字典 d dic...

python3字典排序

說實話,對字典進行排序,這個說法本身就有問題,實際上,你無法對操縱字典說,字典,在你的底層實現裡,你就得按照我指定的順序來排列,如果這樣的話,字典就喪失了它的速度優勢,它也不是乙個字典了.好了,廢話不多說,我這裡稍微記錄一下我的做法吧.python2裡面原來是有dict.iteritems這樣乙個函...