欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python如何實現(xiàn)多層級自動賦值字典

 更新時間:2023年08月12日 10:15:16   作者:小胖_@  
這篇文章主要介紹了python如何實現(xiàn)多層級自動賦值字典問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教

python多層級自動賦值字典

dict 只能單層級賦值

item['20161101'] = 2

defaultdict 只能雙層級賦值

item['20161101']["age"] = 2

使用方法:

import collections
bag = ['apple', 'orange', 'cherry', 'apple','apple', 'cherry', 'blueberry']
count = collections.defaultdict(int)
for fruit in bag:
    count[fruit] += 1
輸出:
defaultdict(<class 'int'>, {'apple': 3, 'orange': 1, 'cherry': 2, 'blueberry': 1})

多層級自動賦值字典

item['20161101']["age"]["444"] = 2

實現(xiàn)多層級自動賦值 除了可以重載__getitem__魔術方法,也可以實現(xiàn)__missing__魔術方法

1.重載__getitem__魔術方法:

def __getitem__(self, item):
? ? try:
? ? ? ? return dict.__getitem__(self, item)
? ? except KeyError:
? ? ? ? value = self[item] = type(self)()
? ? ? ? return value

2.實現(xiàn)__missing__魔術方法:

def __missing__(self, key):
?? ?value = self[key] = type(self)()
?? ?return value

3.使用方法:

class multidict(dict):
def __getitem__(self, item):
?? ?try:
?? ? ? ?return dict.__getitem__(self, item)
?? ?except KeyError:
?? ? ? ?value = self[item] = type(self)()
?? ? ? ?return value
item = multidict()
item['20161101']["age"] = 20
item['20161102']['num'] = 30
print(item)

python字典一鍵賦多值

方案一

(1) list作為dict的值,值允許重復,append添加值

key = 0
value = [1,5]
exp = dict()
exp.setdefault(key,[]).append(value)?
value = [2,5]
exp.setdefault(key,[]).append(value)
print(exp)

輸出:

{0: [[1, 5], [2, 5]]}

(2)set作為dict的值,值不允許重復,add添加值

key = 0
value = 1
exp = dict()
exp.setdefault(key,set()).add(value)?
value = 2
exp.setdefault(key,set()).add(value)
print(exp)

輸出:

{0: {1, 2}}

方案二

使用collections.defaultdict方法

(1)collections.defaultdict(list),值可以重復

import collections
key = 0
value = 1
exp = collections.defaultdict(list)
exp[key].append(value)
value = 1
exp[key].append(value)
print(exp)

輸出:

defaultdict(<class 'list'>, {0: [1, 1]})

(2)collections.defaultdict(set),值不允許重復

import collections
key = 0
value = 1
exp = collections.defaultdict(set)
exp[key].add(value)
value = 1
exp[key].add(value)
value = 5
exp[key].add(value)
print(exp)

輸出:

defaultdict(<class 'set'>, {0: {1, 5}}) 

總結

以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關文章

最新評論