【问题标题】:List of dictionaries: loop through key contents字典列表:遍历关键内容
【发布时间】:2018-05-08 12:15:48
【问题描述】:

对于看似令人困惑的标题,我深表歉意,希望代码有助于澄清问题。

我有一个如下所示的 python 数据结构:

people = [
  {
    'id': 1,
    'name': 'Ada',
    'age': 55
  },
  {
    'id': 2,
    'name': 'Bart',
    'age': 46
  },
  {
    'id': 3,
    'name': 'Chloe',
    'age': 37
  },
  {
    'id': 4,
    'name': 'Dylan',
    'age': 28
  }
]

我想实现以下目标:

1, Ada, 55
2, Bart, 46
3, Chloe, 37
4, Dylan, 28

不必像person['key'] 那样处理每个字典键,而只需key;像这样:

# BOGUS CODE, WON'T WORK
for (id, name, age) in people:
  print('{}, {}, {}'.format(id, name, age))

(奇怪地打印出name, id, age) 提前致谢!

PS:奖金问题!同质字典/对象的列表/数组是否有特定名称(也在 Python 之外)? 同质词典列表 看起来还蛮拗口的。

【问题讨论】:

  • print('{0}, {1}, {2}'.format(id, name, age)) ?
  • @Mika72,这不起作用,请注意 OP 正在遍历字典列表。
  • for dict_ in people: print("{id}, {name}, {age}".format(**dict_))

标签: python python-3.x loops data-structures


【解决方案1】:

你可以这样做:

for person in people:
    person_id, name, age = person['id'], person['name'], person['age']
    print(person_id, name, age)

在 Python 3.6(从 3.7 开始正式支持)中,您也可以这样做(前提是值的定义与您在原始问题中向我们展示的顺序完全相同):

for person in people:
    person_id, name, age = person.values()
    print(person_id, name, age)

但是,这取决于字典的定义完全,就像在您的示例中一样。如果值的顺序发生变化,代码就会中断,因为值也会混合。

提示:我故意将我的变量命名为 person_id 而不是 id,因为它是隐藏内置变量和/或函数的反模式,而 there's a built-in called id .

【讨论】:

  • 你是对的。我认为这是 OP 中的确切顺序。我编辑了答案以更好地反映这些信息。
  • 被排序的dicts仍然是python 3.6中的一个实现细节。在 3.7 之前你不应该依赖它。
【解决方案2】:

您可以使用operator.itemgetter()map()

In [31]: from operator import itemgetter

In [32]: list(map(itemgetter('id', 'name', 'age'), people))
Out[32]: [(1, 'Ada', 55), (2, 'Bart', 46), (3, 'Chloe', 37), (4, 'Dylan', 28)]

但请注意,如果您想要所有键中的所有值,您可以简单地在列表推导中使用dict.values() 来获取所有相应的值。

In [33]: [d.values() for d in people]
Out[33]: 
[dict_values([1, 'Ada', 55]),
 dict_values([2, 'Bart', 46]),
 dict_values([3, 'Chloe', 37]),
 dict_values([4, 'Dylan', 28])]

【讨论】:

    【解决方案3】:
    for find in people:
        print('{0}, {1}, {2}'.format(find["id"], find["name"], find["age"]))
    

    会起作用的

    【讨论】:

    • 虽然我确实熟悉传统方法,但我想达到相同的结果 不必像 person['key'] 那样处理每个字典键,而只需 key >>
    【解决方案4】:

    您可以使用__iter__ 方法构建一个小类:

    class Group:
      def __init__(self, d):
         self.__dict__ = d
    
    class People:
       def __init__(self, data):
         self.data = data
       def __iter__(self):
         for i in self.data:
           d = Group(i)
           yield d.id, d.name, d.age
    
    people = [{'age': 55, 'id': 1, 'name': 'Ada'}, {'age': 46, 'id': 2, 'name': 'Bart'}, {'age': 37, 'id': 3, 'name': 'Chloe'}, {'age': 28, 'id': 4, 'name': 'Dylan'}]
    for a, b, c in People(people):
       print('{} {} {}'.format(a, b, c))
    

    输出:

    1 Ada 55
    2 Bart 46
    3 Chloe 37
    4 Dylan 28
    

    【讨论】:

      猜你喜欢
      • 2020-07-18
      • 1970-01-01
      • 2016-10-10
      • 2019-11-29
      相关资源
      最近更新 更多