如何使用嵌套词典的名称?

2024-09-27 22:23:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用嵌套在列表中的词典编写一个程序。我想在遍历列表时打印每本词典的名称,但不知道如何在不调用词典的全部内容的情况下打印。这是我的密码:

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.

一切正常,我只需要把字典的名字打印出来。解决办法是什么?你知道吗


Tags: 列表songfoodisonsamcountryfavorite
3条回答

基本上,您要做的是打印变量的名称。当然,这是不建议的。如果你真的想这么做,你应该看看这个帖子: How can you print a variable name in python?

我要做的是,将词典的名称存储在列表中。您可以将“people=[sam,dave]”更改为“people=[[“sam”,sam],“dave”,dave]]”。这样,person[0]就是这个人的名字,person[1]包含这个信息。你知道吗

列表中的值不再是变量。它们不是由某个命名空间中的名称来引用的,而是由一个整数来引用的,该整数指示它们与列表前面的偏移量(01,…)。你知道吗

如果要将每个dict数据与某个名称相关联,则必须显式地进行。有两个常规选项,具体取决于负责跟踪名称的人员:人员集合或集合中的每个人员。你知道吗

第一个也是最简单的是^{}——与普通的dict不同,它将保持列表中人员的顺序。你知道吗

from collections import OrderedDict

sam = {
  'food': 'tortas',
  'country': 'Mexico',
  'song': 'Dream On',
  }
dave = {
  'food': 'spaghetti',
  'country': 'USA',
  'song': 'Sweet Home Alabama',
  }
# The OrderedDict stores each person's name.
people = OrderedDict([('Sam', sam), ('Dave', dave)])

for name, data in people.items():
    # Name is a key in the OrderedDict.
    print('Name: ' + name)
    for key, value in sorted(data.items()):
        print('  {0}: {1}'.format(key.title(), value))

或者,您可以将每个人的名字存储在他或她自己的dict。。。假设你被允许更改那些词典的内容。(另外,您不希望向数据字典中添加任何要求您更改/更新数据的内容。由于大多数人改变他们最喜欢的食物或歌曲的频率远远超过他们改变自己的名字,这可能是安全的。)

sam = {
# Each dict has a new key: 'name'.
  'name': 'Sam',
  'food': 'tortas',
  'country': 'Mexico',
  'song': 'Dream On',
  }
dave = {
  'name': 'Dave',
  'food': 'spaghetti',
  'country': 'USA',
  'song': 'Sweet Home Alabama',
  }
people = [sam, dave]

for data in people:
    # Name is a value in the dict.
    print('Name: ' + data['name'])
    for key, value in sorted(data.items()):
        # Have to avoid printing the name again.
        if 'name' != key:
            print('  {0}: {1}'.format(key.title(), value))

请注意,如何打印数据取决于是将名称存储在集合(OrderedDict变量)中,还是存储在每个人的dictlist变量)中。你知道吗

(更)正确的方法是构造一个dictdict,例如:

people = {'sam': {'food' : 'tortas',
                  'country' : 'mexico',
                  'song' : 'Dream On',
                  },
          'dave': {'food' : 'spaghetti',
                   'country' : 'USA',
                   'song' : 'Sweet Home Alabama',
                   }
           }

然后您可以简单地执行以下操作:

for name, person in people.items():
    for key, value in sorted(person.items()):
        print(name + "'s favorite " + key + " is " + value + ".")

这将打印以下内容:

dave's favorite country is USA.
dave's favorite food is spaghetti.
dave's favorite song is Sweet Home Alabama.
sam's favorite country is mexico.
sam's favorite food is tortas.
sam's favorite song is Dream On.

作为补充说明,在print语句中使用字符串格式更具可读性:

print("{0}'s favorite {1} is {2}".format(name, key, value))

相关问题 更多 >

    热门问题