【发布时间】:2016-09-13 01:54:42
【问题描述】:
我正在编写一个使用嵌套在列表中的字典的程序。我想在遍历列表时打印每个字典的名称,但不知道如何在不调用字典的全部内容的情况下执行此操作。这是我的代码:
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'成为键。
标签: python python-3.x dictionary nested