使用namedtuple作为字典键会引发错误

问题描述 投票:1回答:1

this answer相关。

我正在使用PyCharm并进行一些预处理以在内存中构建多对多关系(最终转储到多个CSV文件)。我使用dictionary作为测试存在和查找主要key给出不同的namedtuple数据的手段。

def insert_where_not_exists(self, path, tag):
    path_id = self.__tbl_path[path]
    tag_id = self.__tbl_tag[tag]

    # Invalid or missing tag, so insert this one
    if tag_id is None or tag_id < 0:
        tag_id = self.__tag_ct
        self.__tag_ct += 1
        self.__tbl_tag[tag] = tag_id

    # We assert that we have the tag stored and an appropriate tag_id
    # Create the relationship between filepath and tag
    relationship = namedtuple("relationship", "tag_id path_id")
    rel = relationship(tag_id=tag_id, path_id=path_id)
    rel_id = self.__tbl_rel.[rel]

    # Invalid or missing relationship, so insert this one
    if rel_id is None or rel_id < 0:
        rel_id = self.__rel_ct
        self.__rel_ct += 1
        self.__tbl_rel[rel] = rel_id

我的问题是当试图查找namedtupledictionary key)以获得相关索引时,PyCharm将此错误抛给我。

"name expected" at:
 rel_id = self.__tbl_rel.[rel]
python dictionary indexing key namedtuple
1个回答
0
投票
rel_id = self.__tbl_rel.[rel]

是无效的语法,它是

rel_id = self.__tbl_rel.rel

要么

rel_id = self.__tbl_rel[rel]

在这种情况下:

rel_id = self.__tbl_rel[rel] 

是正确的。

© www.soinside.com 2019 - 2024. All rights reserved.