问题
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 thenamedtuple
definition)tuple.field_name
returns the field namedfield_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