簡體   English   中英

如何從一個字典中使用相同的鍵打印兩個字典值?

[英]How can I print two dict values with the same key from one dict?

我正在使用Python組織電影作品列表,以進行學術作業。 提交截止日期已經過去; 我只想了解它在未來的運作方式。

這是代碼:

movies = {

2005: ['Munich', 'Steven Spielberg'],
2006: ['The Prestige', 'Christopher Nolan'],
2006: ['The Departed', 'Martin Scorsese'],
2007: ['Into the Wild', 'Sean Penn'],
2008: ['The Dark Knight', 'Christopher Nolan'],
2009: ['Mary and Max', 'Adam Elliot'],
2010: ['The King\"s Speech', 'Tom Hooper'],
2011: ['The Artist', 'Michel Hazanavicius'],
2011: ['The Help', 'Tate Taylor'],
2012: ['Argo', 'Ben Affleck'],
2013: ['12 Years a Slave', 'Steve McQueen'],
2014: ['Birdman', 'Alejandro G. Inarritu'],
2015: ['Spotlight', 'Tom McCarthy'],
2016: ['The BFG', 'Steven Spielberg']

}

userInput = int(input('Enter a year between 2005 and 2016: \n'))

print(movies[userInput])

如果我選擇只有一個條目的年份,則打印報表效果很好。 如果用戶輸入“ 2006”,則應該顯示兩個標題,但是我只獲得了2006鍵的后一個值。 我究竟做錯了什么?

鍵對於字典必須是唯一的。 因此,如果將條目添加到字典中,它將覆蓋使用相同鍵的任何條目。

如果您堅持使用年份作為關鍵字(不知道您的作業是否出於某種奇怪的原因而需要這樣做),則可以將條目放入類似

{
   2005: [('Munich', 'Steven Spielberg'), ('King Kong', 'Peter Jackson')],
   ...
}

但這需要一些其他技術,例如使用setdefault()defaultdict (或在添加新項目之前手動檢查鍵是否已存在)。

請注意,在我的示例中,我使用了一個列表來存儲相似元素,並使用元組來存儲不同元素(標題/導演)。 這可能是一個好習慣。

您可以像這樣重組字典:

movies = {
    2005: [('Munich', 'Steven Spielberg')],
    2006: [('The Prestige', 'Christopher Nolan'), ('The Departed', 'Martin Scorsese')],
    2007: [('Into the Wild', 'Sean Penn')],
    2008: [('The Dark Knight', 'Christopher Nolan')],
    2009: [('Mary and Max', 'Adam Elliot')],
    2010: [('The King\"s Speech', 'Tom Hooper')],
    2011: [('The Artist', 'Michel Hazanavicius'), ('The Help', 'Tate Taylor')],
    2012: [('Argo', 'Ben Affleck')],
    2013: [('12 Years a Slave', 'Steve McQueen')],
    2014: [('Birdman', 'Alejandro G. Inarritu')],
    2015: [('Spotlight', 'Tom McCarthy')],
    2016: [('The BFG', 'Steven Spielberg')]
}

電影是元組(title, director) ,而年份條目是電影列表。 選擇一年會給你看電影的清單,

>>> print(movies[2006])
[('The Prestige', 'Christopher Nolan'), ('The Departed', 'Martin Scorsese')]

然后您可以通過遍歷列表來提取標題或導演。

>>> print([movie[0] for movie in movies[2006]])
['The Prestige', 'The Departed']

>>> print([movie[1] for movie in movies[2006]])
['Christopher Nolan', 'Martin Scorsese']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM