繁体   English   中英

如何从类实例列表创建字典,使用其中一个属性作为键。

[英]How to create a dictionary from a list of class instances, using one of the attributes as the key.

我有一个函数 (createList),它从文本文件中读取并从文件中的每一行创建类实例。 这个函数然后返回一个类实例列表。 现在我想要做的是使用其中一个属性作为键从这个列表创建一个字典。

def createDict():
    list = createList()
    fileAsDict = {}
    for i in list:
        fileAsDict[i.name] = i

    return fileAsDict

这似乎是一个简单的解决方案,但我注意到文本文件中的多个实例具有相同的“键”。 我写的代码没有处理这个问题,每次找到相同的 i.name 时都会覆盖键的值。 我想要的是将值存储在列表中,因此当我调用键时,它会打印具有该属性的所有类实例。

我发现了一些提示,例如

for key, val in l:
d.setdefault(key, []).append(val)

但我不知道如何在我的代码中实现它。

您使用setdefault在正确的轨道上。 你只需要用i.name替换key 这是一个显示逻辑的简单示例实现:

>>> # create a dummy class, so we can put some
>>> # instances in a list
>>> class Dummy:
    def __init__(self, name):
        self.name = name


>>> # create a list with Dummy() class instances. Uh oh! some of them have the
>>> # same value for self.i
>>> classes = [Dummy('a'), Dummy('b'), Dummy('b'), Dummy('c'), Dummy('d')]
>>> 
>>> # now we'll create the dictionary to hold the class instances.
>>> classes_dict = {}
>>> 
>>> # Here we are iterating over the list. For every element in the list,
>>> # we add to the dict using setdefault(). This means that if the element
>>> # key is already in the dict, we append it to the key's list. Otherwise,
>>> # we create a key with a new, empty list.
>>> for each_class in classes:
    classes_dict.setdefault(each_class.name, []).append(each_class)


>>> # final result
>>> classes_dict {'a': [<__main__.Dummy object at 0x0000020B79263550>],
 'b': [<__main__.Dummy object at 0x0000020B792BB1D0>,
     <__main__.Dummy object at 0x0000020B792BB320>],
 'c': [<__main__.Dummy object at 0x0000020B792BB358>],
 'd: [<__main__.Dummy object at 0x0000020B792BB390>]}
>>> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM