Python 将多列表转换为dict的dict

Python 将多列表转换为dict的dict,python,class,dictionary,Python,Class,Dictionary,我有一个自定义类来模拟表中的一行(在数据库概念中),每一列都是一个字符串 class Row: def __init__(self, filename, message, version): self.filename = filename self.message = message self.version = version 我用一个列表来存储它们 假设我不知道每列的范围,我想把这个“表”转换成一个dict的dict, 这样,查询filename=OOO和ve

我有一个自定义类来模拟表中的一行(在数据库概念中),每一列都是一个字符串

class Row:
  def __init__(self, filename, message, version):
    self.filename = filename
    self.message = message
    self.version = version
我用一个列表来存储它们

假设我不知道每列的范围,我想把这个“表”转换成一个dict的dict, 这样,查询
filename=OOO
version=XXXX
的所有行就更容易了。
有什么更好的方法?现在我可以遍历所有行并为特定列构建范围,但这是一种意大利面代码。

最简单的可能是这样的。如果您知道您的行是不可变的,那么可以提供一个hash方法,这样看起来会更好一些

#!/usr/local/cpython-3.3/bin/python

class Row:
    def __init__(self, filename, message, version):
        self.filename = filename
        self.message = message
        self.version = version

    def __str__(self):
        return '{} {} {}'.format(self.filename, self.message, self.version)

    __repr__ = __str__

def main():
    list_ = [
        Row('abc', 'message1', 'version1'),
        Row('def', 'message2', 'version2'),
        Row('ghi', 'message3', 'version3'),
        Row('jkl', 'message4', 'version4'),
        Row('mno', 'message5', 'version5'),
        ]

    dict_ = {}
    for row in list_:
        tuple_ = (row.filename, row.version)
        dict_[tuple_] = row

    sought = ('def', 'version2')
    print(dict_[sought])

main()

您需要将
设置为小写。此外,将
大写也将遵循惯例。