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

python如何實(shí)現(xiàn)多層級(jí)自動(dòng)賦值字典

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

python多層級(jí)自動(dòng)賦值字典

dict 只能單層級(jí)賦值

item['20161101'] = 2

defaultdict 只能雙層級(jí)賦值

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})

多層級(jí)自動(dòng)賦值字典

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

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

1.重載__getitem__魔術(shù)方法:

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

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

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的值,值允許重復(fù),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的值,值不允許重復(fù),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),值可以重復(fù)

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),值不允許重復(fù)

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}}) 

總結(jié)

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論