Python 打印具有多个值的元组键字典

Python 打印具有多个值的元组键字典,python,dictionary,Python,Dictionary,我有一本字典,作者的姓和名是关键,书、数量和价格是价值。我想把它们按作者姓名的字母顺序打印出来,然后再按书名 The author is: Dickens, Charles The title is: Hard Times The qty is: 7 The price is: 27.00 ---- The author is: Shakespeare, William The title is: Macbeth The qty is: 3 The price is: 7.99 ---- The

我有一本字典,作者的姓和名是关键,书、数量和价格是价值。我想把它们按作者姓名的字母顺序打印出来,然后再按书名

The author is: Dickens, Charles
The title is: Hard Times
The qty is: 7
The price is: 27.00
----
The author is: Shakespeare, William
The title is: Macbeth
The qty is: 3
The price is: 7.99
----
The title is: Romeo And Juliet
The qty is: 5
The price is: 5.99 
我对字典很陌生,不懂如何给字典分类。到目前为止,我的代码是:

def displayInventory(theInventory):
    theInventory = readDatabase(theInventory)
    for key in theInventory:
        for num in theInventory[key]:
            print("The author is", ' '.join(str(n) for n in key))
            print(' '.join(str(n) for n in num), '\n')
我从中读到的这本词典在印刷时是这样的:

defaultdict(<class 'list'>, {('Shakespeare', 'William'): [['Rome And Juliet', '5', '5.99'], ['Macbeth', '3', '7.99']], ('Dickens', 'Charles'): [['Hard Times', '7', '27.00']]})
defaultdict(,{(“莎士比亚”,“威廉”):[[[罗马与朱丽叶”,“5”,“5.99”,“麦克白”,“3”,“7.99]”],(“狄更斯”,“查尔斯”):[[艰难时期”,“7”,“27.00']]
关键是使用sorted()按关键字对字典进行排序,然后对字典值使用sort()。这是必要的,因为您的值实际上是一个列表列表,并且您似乎只希望按每个子列表中的第一个值对它们进行排序

theInventory = {('Shakespeare', 'William'): [['Rome And Juliet', '5', '5.99'], ['Macbeth', '3', '7.99']], ('Dickens', 'Charles'): [['Hard Times', '7', '27.00']]}

for Author in sorted(theInventory.keys()):
    Author_Last_First = Author[0]+", "+Author[1]
    Titles = theInventory[Author]
    Titles.sort(key=lambda x: x[0])
    for Title in Titles:
        print("Author: "+str(Author_Last_First))
        print("Title: "+str(Title[0]))
        print("Qty: "+str(Title[1]))
        print("Price: "+str(Title[2]))
        print("\n")

这就是你的想法吗?当然,您可以将其放在函数中以使调用更容易。

fwiw,camelCase在Python中非常少见;几乎所有的东西都是用蛇壳写的。:)

我会这样做:

for names, books in sorted(inventory.items()):
    for title, qty, price in sorted(books):
        print("The author is {0}".format(", ".join(names)))
        print(
            "The book is {0}, and I've got {1} of them for {2} each"
            .format(title, qty, price))
        print()
暂时忽略

这里有一些小技巧

  • 首先,
    inventory.items()。然后我可以直接排序,因为元组按元素排序-也就是说,
    (1,“z”)
    (2,“a”)
    之前排序。因此Python将首先比较键,键本身就是元组,所以它将比较姓氏和姓氏。正是你想要的

  • 我同样可以直接对
    书籍进行排序,因为我实际上想按标题进行排序,而标题是每个结构中的第一件事

  • 我可以
    .join
    直接连接
    名称
    元组,因为我已经知道其中的所有内容都应该是字符串,如果不是这样的话,就会出现问题

  • 然后我到处使用
    .format()
    ,因为
    str()
    有点难看


字典本质上是无序的,因此您不会对它们进行排序。这个相关的问题似乎给出了一个很好的答案:这个想法是从字典内容中产生一个列表并对其进行排序。我第一次问错了。我已经把我在问题中列出的清单包括在内。
.sort
意味着你修改了原始的dict,这可能是不礼貌的。元组解包比显式索引更容易遵循。您不需要
.keys()
;迭代dict直接生成其键。而且
大写字母下划线
真的很奇怪:)谢谢你的想法:)为什么你更喜欢.format()而不是str()?
str()
和串联需要将字符串拆分成碎片,而格式字符串让你一眼就能大致看到结果
.format
作为一种方法,也更容易包装。连接是O(n²),并不是说它很重要。这里有没有一种方法可以将其格式化,以便专门查看作者的作品?如果作者不在字典中,这会产生错误吗?好吧,您可以将内部循环移动到函数中,然后执行
books=inventory[“Shakespeare”,“William”]
以获得正确的图书列表。是的,您将得到一个
键错误