Indexing a namedtuple nested in a dictionary

大憨熊 提交于 2019-12-11 17:59:51

问题


I'm looking to store a named tuple inside a dictionary. That parts easy. I don't know how to reference an individual bit in the namedtuple following that though.

I know that I could just use a dictionary and make life easier, but in the case where you have values you know you don't want to change, it'd be nice to use a namedtuple here (more so just out of interest - I realize strings are immutable as well).

from collections import namedtuple

Rec = namedtuple('name', ['First', 'Middle', 'Last'])
name = Rec('Charles', 'Edward', 'Bronson')

info = dict(identity=name)

print(name.First)
print(info['identity'])
print(type(info['identity']))

Results:

Charles
name(First='Charles', Middle='Edward', Last='Bronson')
<class '__main__.name'>

I expect to be able to access name.First through calling info['identity'][name.First] or something similar, but I can't seem to index inside the nested namedtuple.


回答1:


as you probably know, namedtuples support multiple types of indexing

  • tuple[0] returns the first field (order is defined from the list of fields you gave during the namedtuple definition)
  • tuple.field_name returns the field named field_name

info['identity'] is the namedtuple you want to index, so let's go :)

print(info['identity'] == name)
# True
print(info['identity'].First)
# Charles
# or
print(info['identity'][0])
# Charles

# OR, splitting the operations
name_field = info['identity']
print(name_field.First)


来源:https://stackoverflow.com/questions/57995861/indexing-a-namedtuple-nested-in-a-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!