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}})
總結
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Windows 安裝 Anaconda3+PyCharm的方法步驟
這篇文章主要介紹了Windows 安裝 Anaconda3+PyCharm的方法步驟,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-06-06詳解JavaScript編程中的window與window.screen對象
這篇文章主要介紹了JavaScript編程中的window與window.screen對象,是JS在瀏覽器中視圖編程的基礎,需要的朋友可以參考下2015-10-10python中以函數(shù)作為參數(shù)(回調函數(shù))的實現(xiàn)方法
這篇文章主要介紹了python中以函數(shù)作為參數(shù)(回調函數(shù))的實現(xiàn)方法,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-01-01