索引嵌套在字典中的namedtuple [英] Indexing a namedtuple nested in a dictionary

查看:75
本文介绍了索引嵌套在字典中的namedtuple的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望将一个命名的元组存储在字典中.那部分容易.不过,我不知道如何在namedtuple中引用单个位.

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.

我知道我可以只使用字典来简化生活,但是如果您拥有不需要更改的值,那么在这里使用一个namedtuple会很好(更多的只是,有趣-我意识到字符串也是不可变的.

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']))

结果:

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

我希望能够通过调用info['identity'][name.First]或类似方法来访问name.First,但是我似乎无法在嵌套的namedtuple中建立索引.

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.

推荐答案

命名元组支持多种类型的索引

as you probably know, namedtuples support multiple types of indexing

  • tuple[0]返回第一个字段(顺序是从您在namedtuple定义期间给出的字段列表中定义的)
  • tuple.field_name返回名为field_name
  • 的字段
  • 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']是您要索引的namedtuple,让我们开始:)

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)

这篇关于索引嵌套在字典中的namedtuple的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆