【问题标题】:Python converting the values from dicts into a tuplesPython将字典中的值转换为元组
【发布时间】:2011-03-13 05:44:22
【问题描述】:

我有一个字典列表,如下所示:

[{'id':1,'name':'Foo'},{'id':2,'name':'Bar'}]

我想将每个字典中的值转换成这样的元组列表:

[(1,'Foo'),(2,'Bar')]

我该怎么做?

【问题讨论】:

    标签: python dictionary tuples


    【解决方案1】:
    >>> l = [{'id':1,'name':'Foo'},{'id':2,'name':'Bar'}]
    >>> [tuple(d.values()) for d in l]
    [(1, 'Foo'), (2, 'Bar')]
    

    【讨论】:

    • @Marco:它为给定的键提供一致的顺序,这个答案没有错。
    • 你不能保证id 总是在name 之前出现,尤其是在不同的版本/实现中。例如,在 IronPython(例如 trypython.org)中输入上述示例当前会给出[('Foo', 1), ('Bar', 2)]。你甚至不能确定两个具有相同键的字典会以相同的顺序给出它们的keys()(它们会用于像这样的简单情况,但这是你不应该依赖的实现细节)。跨度>
    • 现在可以使用了,Dictionaries preserve insertion order. Note that updating a key does not affect the order. Keys added after deletion are inserted at the end. link
    【解决方案2】:

    请注意,SilentGhost 答案中的方法不能保证每个元组的顺序,因为字典及其 values() 没有固有顺序。因此,在一般情况下,您可能会得到('Foo', 1)(1, 'Foo')

    如果这是不可接受的,并且您肯定首先需要 id,您必须明确地这样做:

    [(d['id'], d['name']) for d in l]
    

    【讨论】:

      【解决方案3】:

      这将始终在定义的order 中将字典转换为元组

      d = {'x': 1 , 'y':2} order = ['y','x'] tuple([d[field] for field in order])

      【讨论】:

      • dicts 现在是有序的(最近的 python 标准承诺),所以现在没有必要了。
      猜你喜欢
      • 2016-06-01
      • 2020-10-03
      • 2016-03-21
      • 2020-09-21
      • 1970-01-01
      • 2022-07-24
      • 1970-01-01
      • 1970-01-01
      • 2022-06-14
      相关资源
      最近更新 更多