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

时间:2015-10-27 13:17:08

标签: python dictionary indexing key namedtuple

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]

1 个答案:

答案 0 :(得分: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] 

是对的。