我正在用嵌套在列表中的词典编写一个程序。我想在遍历列表时打印每本词典的名称,但不知道如何在不调用词典的全部内容的情况下打印。这是我的密码:
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.
一切正常,我只需要把字典的名字打印出来。解决办法是什么?你知道吗
基本上,您要做的是打印变量的名称。当然,这是不建议的。如果你真的想这么做,你应该看看这个帖子: How can you print a variable name in python?
我要做的是,将词典的名称存储在列表中。您可以将“people=[sam,dave]”更改为“people=[[“sam”,sam],“dave”,dave]]”。这样,person[0]就是这个人的名字,person[1]包含这个信息。你知道吗
列表中的值不再是变量。它们不是由某个命名空间中的名称来引用的,而是由一个整数来引用的,该整数指示它们与列表前面的偏移量(
0
,1
,…)。你知道吗如果要将每个
dict
数据与某个名称相关联,则必须显式地进行。有两个常规选项,具体取决于负责跟踪名称的人员:人员集合或集合中的每个人员。你知道吗第一个也是最简单的是^{} ——与普通的
dict
不同,它将保持列表中人员的顺序。你知道吗或者,您可以将每个人的名字存储在他或她自己的
dict
。。。假设你被允许更改那些词典的内容。(另外,您不希望向数据字典中添加任何要求您更改/更新数据的内容。由于大多数人改变他们最喜欢的食物或歌曲的频率远远超过他们改变自己的名字,这可能是安全的。)请注意,如何打印数据取决于是将名称存储在集合(
OrderedDict
变量)中,还是存储在每个人的dict
(list
变量)中。你知道吗(更)正确的方法是构造一个
dict
的dict
,例如:然后您可以简单地执行以下操作:
这将打印以下内容:
作为补充说明,在
print
语句中使用字符串格式更具可读性:相关问题 更多 >
编程相关推荐