Python如何把 dict 快速转换为namedtuple,下面的代码可能让你更容易理解:
简介: Python编程:namedtuple命名元组和dict字典相互转换 from collections import namedtuple dct = { "name": "Tom", "age": 24 } Person = namedtuple("Person", ["name", "age"]) # 字典转为namedtuple person = Person._make(dct) print(person) # Person(name='name', age='age') # namedtuple...
使Python脱颖而出的功能之一是OrderedDict类,它是一个字典子类,可以记住插入项目的顺序。但是,在某些情...
Python编程:namedtuple命名元组和dict字典相互转换 from collections import namedtuple dct = { "name": "Tom", "age": 24 } Person = namedtuple("Person", ["name", "age"]) # 字典转为namedtuple person = Person._make(dct) print(person) # Person(name='name', age='age') # namedtuple转为字典...
namedtuple!对,就是它! 将我们的函数转换为使用namedtuple: fromcollectionsimportnamedtuple ... Color = namedtuple("Color","r g b alpha") ...defconvert_string_to_color(desc:str, alpha:float=0.0):ifdesc =="green":returnColor(r=50, g=205, b=50, alpha=alpha)elifdesc =="blue":returnColor...
Python如何把 dict 快速转换为namedtuple 文章被收录于专栏:Python七号 下面的代码可能让你更容易理解: 本文参与腾讯云自媒体同步曝光计划,分享自微信公众号。 原始发表:2022-08-02,如有侵权请联系cloudcommunity@tencent.com删除
dct={"name":"Tom","age":24}Person=namedtuple("Person",["name","age"])# 字典转为namedtupleperson=Person._make(dct)print(person)# Person(name='name', age='age')# namedtuple转为字典print(person._asdict())# OrderedDict([('name', 'name'), ('age', 'age')]) ...
>>> p.x + p.y# fields also accessible by name33>>> d = p._asdict()# convert to a dictionary>>> d['x']11>>> Point(**d)# convert from a dictionaryPoint(x=11, y=22) >>> p._replace(x=100)# _replace() is like str.replace() but targets named fieldsPoint(x=100, y=...
有lat/long两个字段latLong = namedtuple('LatLong', 'lat long')delhi_data = ('Delhi NCR', 'IN', 21.935, latLong(28.618, 77.208)) # 用 _make() 通过接受一个可迭代对象来生成这个类的一个实例,作用跟City(*delhi_data)相同delhi = city._make(delhi_data) # _asdict() 把具名元组以 ...
>>> d = p._asdict() # convert to a dictionary >>> d['x'] 11 >>> Point(**d) # convert from a dictionary Point(x=11, y=22) >>> p._replace(x=100) # _replace() is like str.replace() but targets named fields Point(x=100, y=22)"""#Validate the field names. At the...