[python]pythonic的字典常用操作


注意:dct代表字典,key代表鍵值

1.判斷字典中某個鍵是否存在

實現

dct.has_key(key)  #False

更Pythonic方法

key in dct  #False

2.獲取字典中的值
你想對key的value加1,首先你要判斷key是否存在,不存在給一個默認值

實現

if key not in dct:
	dct[key] = 0
dct[key] += 1

更Pythonic方法

dct[key] = dct.get(key, 0) + 1

如果key存在則返回對應的value,如果不存在返回默認值(這里是0)

3.字典的value是可變對象
如果這個可變對象為list,你想初始化並修改它們。
實現

for (key, value) in data:
	# 把key和value以元組的結構存到list中
	if key in dct:
		dct[key].append(value)
	else:
		dct[key] = [value]

更Pythonic方法

for (key, value) in data:
	dct.setdefault(key, []).append(value)

更更Pythonic方法

dct = defaultdict(list)  # 字典value的默認值為[]
for (key, value) in data:
	dct[key].append(value)

dct = defaultdict(list) 等同於 dct.setdefault(key, []) 據說前者快。
defaultdict詳解

4.合並兩個字典

a = {'a':1,'b':2}
b = {'c':3}

# 方法1
new_dict = a
new_dict.update(b)

# 方法2
new_dict = dict(a.items()+b.items())

# 方法3(Pythonic)
new_dict = dict(a, **b)

如果合並兩個字典的時候,如果兩個字典有相同的key,則把value相加

from collections import Counter
a = {'a':1,'b':2}
b = {'a':1}

c = Counter(a) + Counter(b)  # 此時c為Counter對象
c = dict(c)  # 轉變成字典
print c
# {'a': 2, 'b': 2}

參考:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM