[英]How can I convert a list of dictionary(in json) into objects in python?
例如:我有這樣
a=[{'id':1,'rating':123,'handle':'roshan'},{'id':2,'rating':423,'handle':'tippi'}]
(可以多於兩個)python中有沒有辦法組織這種數據?
如果您只想將其轉換為具有相同名稱屬性的 object ,我建議使用namedtuple
,因為它提供的摩擦最小,您可以使用雙星運算符將 dict 的內容轉儲到其中。
例子:
from collections import namedtuple
for data in [
{'id': 1, 'rating': 123, 'handle': 'roshan'},
{'id': 2, 'rating': 423, 'handle': 'tippi'}
]:
Object = namedtuple("Object", ["id", "rating", "handle"])
obj = Object(**data)
print(obj.id, obj.rating, obj.handle)
有關命名元組的更多詳細信息,請參閱文檔https://docs.python.org/3/library/collections.html#collections.namedtuple
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.