Python简易字典库easydict和addict
生活随笔
收集整理的這篇文章主要介紹了
Python简易字典库easydict和addict
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 簡介
- 類似項目
- 安裝
- 一、easydict
- 初試
- 加載已解析的JSON內容
- 易于取值和設值
- 仍然是字典
- 對象封裝
- 二、addict
- 初試
- 嵌套數據類型
- 要記住的點
- 變回內置字典
- 統計
- 更新
- 數組
- 備注
- 案例
- 目錄樹
- 樹結構
- 參考文獻
簡介
easydict 允許 JavaScript 一樣通過 . 訪問值(屬性)。
addict 可以輕松地設置嵌套字典。
類似項目
| easydict | 175 |
| addict | 2.1k |
| Box | 1.7k |
安裝
pip install easydict pip install addict一、easydict
初試
from easydict import EasyDict as edictd = edict({'foo': 3, 'bar': {'x': 1, 'y': 2}}) print(d.foo) # 3 print(d.bar.x) # 1d = edict(foo=3) print(d.foo) # 3加載已解析的JSON內容
from json import loads from easydict import EasyDict as edictj = """{ "Buffer": 12, "List1": [{"type" : "point", "coordinates" : [100.1,54.9] },{"type" : "point", "coordinates" : [109.4,65.1] },{"type" : "point", "coordinates" : [115.2,80.2] },{"type" : "point", "coordinates" : [150.9,97.8] } ] }""" d = edict(loads(j)) print(d.Buffer) # 12 print(d.List1[0].coordinates[1]) # 54.9易于取值和設值
from easydict import EasyDictd = EasyDict() d.foo = 3 print(d.foo) # 3仍然是字典
from easydict import EasyDictd = EasyDict(log=False) d.debug = True print(d.items()) # dict_items([('log', False), ('debug', True)])對象封裝
from easydict import EasyDictclass Flower(EasyDict):power = 1f = Flower({'height': 12}) print(f.power) # 1 print(f['height']) # 12二、addict
初試
from addict import Dictmapping = Dict() mapping.a.b.c.d.e = 2 print(mapping) # {'a': {'b': {'c': {'d': {'e': 2}}}}}嵌套數據類型
from addict import Dictmapping = {'a': [{'b': 3}, {'b': 3}]} dictionary = Dict(mapping) print(dictionary.a[0].b) # 3 print(mapping['a'] is dictionary['a']) # False,引用不同當直接使用 list 設值時,引用相同
from addict import Dicta = Dict() b = [1, 2, 3] a.b = b print(a.b is b) # True要記住的點
變回內置字典
若覺得不安全,可以用 to_dict() 變回內置字典
from addict import Dictmy_addict = Dict() my_addict.a.b.c = 2 regular_dict = my_addict.to_dict() print(type(regular_dict)) # <class 'dict'> print(regular_dict) # {'a': {'b': {'c': 2}}}統計
深度嵌套字典讓統計變得相當便利
from addict import Dictdata = [{'born': 1980, 'gender': 'M', 'eyes': 'green'},{'born': 1980, 'gender': 'F', 'eyes': 'green'},{'born': 1980, 'gender': 'M', 'eyes': 'blue'},{'born': 1980, 'gender': 'M', 'eyes': 'green'},{'born': 1980, 'gender': 'M', 'eyes': 'green'},{'born': 1980, 'gender': 'F', 'eyes': 'blue'},{'born': 1981, 'gender': 'M', 'eyes': 'blue'},{'born': 1981, 'gender': 'F', 'eyes': 'green'},{'born': 1981, 'gender': 'M', 'eyes': 'blue'},{'born': 1981, 'gender': 'F', 'eyes': 'blue'},{'born': 1981, 'gender': 'M', 'eyes': 'green'},{'born': 1981, 'gender': 'F', 'eyes': 'blue'} ]counter = Dict()for row in data:born = row['born']gender = row['gender']eyes = row['eyes']counter[born][gender][eyes] += 1print(counter) # {1980: {'M': {'green': 3, 'blue': 1}, 'F': {'green': 1, 'blue': 1}}, 1981: {'M': {'blue': 2, 'green': 1}, 'F': {'green': 1, 'blue': 2}}}更新
from addict import Dictd = {'a': {'b': 3}} d.update({'a': {'c': 4}}) print(d) # {'a': {'c': 4}}d = Dict({'a': {'b': 3}}) d.update({'a': {'c': 4}}) print(d) # {'a': {'b': 3, 'c': 4}}數組
想要類似 defaultdict(list) 一樣工作,可判斷類型并轉換為 list
from addict import Addictd = Addict() # d['a']['b'].append(1) # 報錯TypeError: 'Dict' object is not callable if isinstance(d['a']['b'], dict):d['a']['b'] = [] d['a']['b'].append(1) print(d) # {'a': {'b': [1]}}或用 try ... except ...
備注
案例
目錄樹
強烈推薦使用 Python樹結構庫treelib
Python表示
樹結構
根據結點路徑保存
from collections import namedtuplefrom addict import AddictNode = namedtuple('Node', ['id', 'name', 'path']) data = [Node(1, 'a', '/1'), # 根節點Node(2, 'b', '/1/2'), # 一級結點Node(3, 'c', '/1/2/3'), # 二級結點Node(4, 'd', '/1/2/4'), # 二級結點 ]tree = Addict() for i in data:current = treepaths = [int(j) for j in i.path.strip('/').split('/')] # 分割為列表length = len(paths)node = {'id': i.id, 'name': i.name}for index, id in enumerate(paths): # 移動current = current[id]if index == length - 1:current.update(node) print(tree) # {1: {2: {3: {'id': 3, 'name': 'c'}, # 4: {'id': 4, 'name': 'd'}, # 'id': 2, # 'name': 'b'}, # 'id': 1, # 'name': 'a'}}放入 child 中
from collections import namedtuplefrom addict import AddictNode = namedtuple('Node', ['id', 'name', 'path']) data = [Node(1, 'a', '/1'), # 根節點Node(2, 'b', '/1/2'), # 一級結點Node(3, 'c', '/1/2/3'), # 二級結點Node(4, 'd', '/1/2/4'), # 二級結點 ]tree = Addict() for i in data:father, current = None, treepaths = [int(j) for j in i.path.strip('/').split('/')] # 分割為列表length = len(paths)node = {'id': i.id, 'name': i.name}for index, id in enumerate(paths): # 移動father, current = current, current[id]# if index == length - 1:# current.update(node)if length != 1: # 根節點不用放if isinstance(father['child'], dict):father['child'] = []father['child'].append(node) print(tree) # {1: {2: {'child': [{'id': 3, 'name': 'c'}, {'id': 4, 'name': 'd'}]}, # 'child': [{'id': 2, 'name': 'b'}]}}TODO:可直接獲取某一結點的樹
參考文獻
總結
以上是生活随笔為你收集整理的Python简易字典库easydict和addict的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何将视频修改成html,如何利用h5将
- 下一篇: QT广告屏(多显示器分屏+全屏显示图片)