多个键值。

时间:2014-05-05 18:09:31

标签: python-3.x dictionary

我有一个从文件中读取内容并将其附加到字典中的函数。文件的内容是作者姓名,书名,数量和价格,它们都以文件中的逗号分隔。作者是所有值的关键。我的代码是:

for line in infile:
    lineList = line.strip("\n").split(",")
    author = lineList[0] + "," + lineList[1]
    book = [lineList[2], lineList[3], lineList[4]]

    theInventory[author] = [book]

它不允许我为作者添加额外的书籍。所以威廉莎士比亚有罗密欧与朱丽叶和麦克白。它将采用罗密欧与朱丽叶,但随后用麦克白作为键的新值来覆盖它。我希望这两本书都是莎士比亚,威廉的价值观。这些是文件的内容:

莎士比亚,威廉,罗密欧与朱丽叶,5,5.99
莎士比亚,威廉,麦克白,3,7.99
狄更斯,查尔斯,艰难时期,7,27.00

2 个答案:

答案 0 :(得分:1)

问题是你每次都在库存中覆盖了作者的条目。因此,每个作者的最后一本书都会出现。这应该可以解决这个错误:

theInventory = {}
for line in infile:
    lineList = line.strip("\n").split(",")
    author = lineList[0] + "," + lineList[1]
    book = [lineList[2], lineList[3], lineList[4]]
    if author not in theInventory:
        theInventory[author] = []
    theInventory[author].append(book)

当然,还有一种更面向对象的方式:

from collections import defaultdict
class Book:
    def __init__(name, price):
        self.name = name
        self.price = price
    def __eq__(self, other):
        if not isinstance(other, Book):
            return False
        return self.name == other.name

inventory = defaultdict(dict)
with open('path/to/file') as infile:
    for lname, fname, title, quantity, price in csv.reader(infile):
        price = float(price)
        quantity = int(quantity)
        author = "%s,%s" %(lname, fname)
        inventory[author][Book(title, price)] = quantity

答案 1 :(得分:1)

问题是您使用[作者]作为每个字段的唯一ID。如果您有2本同一作者的书籍,则会覆盖之前的项目。

我不建议使用作者为该作者获取多本书。以这种方式将数据绑定在一起是不好的做法。

我会创建一个图书对象列表,每个图书对象都有你描述的属性。然后我会查询包含“莎士比亚”作者的所有书籍的书籍清单。

这也允许您以除作者之外的方式查询数据。

相关问题