Python:将列表附加为字典中的键

时间:2014-11-25 15:44:49

标签: python-3.x dictionary

def classify(kingdom, species):
""" (list of str, list of str) -> dict

classifies each of the species in the right class in the format of a dictionary
PRECONDITION: len(kingdom) = len(species)

>>>classify(['Animal', 'Animal', 'Plant', 'Protist'], ['Dog', 'Cat', 'Daffodil', 'Plankton'])
{'Animal' : ['Dog', 'Cat'], 'Plant' : ['Daffodil'], 'Protist' : ['Plankton']}
""""

我正在尝试完成此功能;但是,我不知道如何将变量分配给使用列表作为值的字典,也不知道如何将新值添加到列表中。

到目前为止,这是我的尝试

def classify(kingdom, species):
d = {}
for j in range(len(kingdom)):
    d[kingdom[j]] = []
for k in range(len(species)):
    d[kingdom[k]].append(species[k])
return d

由于某种原因,返回错误的结果。

>>>classify(['Animal', 'Animal', 'Plant', 'Protist'], ['Dog', 'Cat', 'Daffodil', 'Plankton'])
{'Protist': ['Dog', 'Cat', 'Daffodil', 'Plankton'], 'Plant': ['Dog', 'Cat', 'Daffodil', 'Plankton'], 'Animal': ['Dog', 'Cat', 'Daffodil', 'Plankton']}

1 个答案:

答案 0 :(得分:1)

两个问题。

首先,在您使用kingdom[1]的任何地方,您应该只使用kingdom。好像你曾经有过一个包含两个子列表的单个列表的函数,并且你没有更新代码以对应新的签名。

其次,执行d[kingdom[j]] = b会导致d中的所有值都指向完全相同的列表。附加到其中一个将导致所有其他的也被附加到其中。只需每次都指定一个全新的列表。

def classify(kingdom, species):
    d = {}
    for j in range(len(kingdom)):
        d[kingdom[j]] = []
    for k in range(len(species)):
        d[kingdom[k]].append(species[k])
    return d

print classify(['Animal', 'Animal', 'Plant', 'Protist'], ['Dog', 'Cat', 'Daffodil', 'Plankton'])

结果:

{'Plant': ['Daffodil'], 'Protist': ['Plankton'], 'Animal': ['Dog', 'Cat']}

奖励:您可能会发现重构代码是值得的。如果dcollections.defaultdict,则可以消除函数中的第一个循环;您不需要设置列表,因为它们将默认创建。

from collections import defaultdict
def classify(kingdom, species):
    d = defaultdict(list)
    for k in range(len(species)):
        d[kingdom[k]].append(species[k])
    return d

如果你遍历列表,你可以使第二个循环更清晰。元素直接而不是遍历它们的索引。

from collections import defaultdict
def classify(kingdom, species):
    d = defaultdict(list)
    for name, kind in zip(species, kingdom):
        d[kind].append(name)
    return d