我正在使用嵌套在列表中的字典編寫程序。我希望在循環列表時打印每個字典的名稱,但不知道如何在不調用字典的全部內容的情況下執行此操作。這裏是我的代碼:如何使用嵌套字典的名稱?
sam = {
'food' : 'tortas',
'country' : 'mexico',
'song' : 'Dream On',
}
dave = {
'food' : 'spaghetti',
'country' : 'USA',
'song' : 'Sweet Home Alabama',
}
people = [sam, dave]
for person in people:
for key, value in sorted(person.items()):
print(#person's name +
"'s favorite " + key + " is " + value + ".")
這裏是輸出:
's favorite country is mexico.
's favorite food is tortas.
's favorite song is Dream On.
's favorite country is USA.
's favorite food is spaghetti.
's favorite song is Sweet Home Alabama.
一切正常,我只需要我的字典的名稱進行打印。什麼是解決方案?
對象在這個意義上不具有「名稱」。你可以做'bob = dave'之類的東西,然後同一個對象有兩個名字。如果你想要這樣的東西,再加上一層嵌套,把「dave」和「sam」作爲鍵。 – BrenBarn