问题:如何将字典转换为元组列表?

如果我有这样的字典:

{ 'a': 1, 'b': 2, 'c': 3 }

如何将其转换为此?

[ ('a', 1), ('b', 2), ('c', 3) ]

以及如何将其转换为此?

[ (1, 'a'), (2, 'b'), (3, 'c') ]

If I have a dictionary like:

{ 'a': 1, 'b': 2, 'c': 3 }

How can I convert it to this?

[ ('a', 1), ('b', 2), ('c', 3) ]

And how can I convert it to this?

[ (1, 'a'), (2, 'b'), (3, 'c') ]

回答 0

>>> d = { 'a': 1, 'b': 2, 'c': 3 }
>>> d.items()
[('a', 1), ('c', 3), ('b', 2)]
>>> [(v, k) for k, v in d.iteritems()]
[(1, 'a'), (3, 'c'), (2, 'b')]

它不是您想要的顺序,但是字典始终没有任何特定的顺序。1对其进行排序或根据需要进行组织。

参见:items()iteritems()


在Python 3.x中,您将不使用iteritems(不再存在),而使用items,它现在返回字典项目的“视图”。看到什么新的Python 3.0文档,以及新的看法文档

1:在Python 3.7中添加了字典的插入顺序保留

>>> d = { 'a': 1, 'b': 2, 'c': 3 }
>>> d.items()
[('a', 1), ('c', 3), ('b', 2)]
>>> [(v, k) for k, v in d.iteritems()]
[(1, 'a'), (3, 'c'), (2, 'b')]

It’s not in the order you want, but dicts don’t have any specific order anyway.1 Sort it or organize it as necessary.

See: items(), iteritems()


In Python 3.x, you would not use iteritems (which no longer exists), but instead use items, which now returns a “view” into the dictionary items. See the What’s New document for Python 3.0, and the new documentation on views.

1: Insertion-order preservation for dicts was added in Python 3.7


回答 1

因为没有其他人做过,所以我将添加py3k版本:

>>> d = { 'a': 1, 'b': 2, 'c': 3 }
>>> list(d.items())
[('a', 1), ('c', 3), ('b', 2)]
>>> [(v, k) for k, v in d.items()]
[(1, 'a'), (3, 'c'), (2, 'b')]

since no one else did, I’ll add py3k versions:

>>> d = { 'a': 1, 'b': 2, 'c': 3 }
>>> list(d.items())
[('a', 1), ('c', 3), ('b', 2)]
>>> [(v, k) for k, v in d.items()]
[(1, 'a'), (3, 'c'), (2, 'b')]

回答 2

您可以使用列表推导。

[(k,v) for k,v in a.iteritems()] 

会得到你[ ('a', 1), ('b', 2), ('c', 3) ]

[(v,k) for k,v in a.iteritems()] 

另一个例子。

如果愿意,请阅读有关列表理解的更多信息,您可以使用它们来做非常有趣。

You can use list comprehensions.

[(k,v) for k,v in a.iteritems()] 

will get you [ ('a', 1), ('b', 2), ('c', 3) ] and

[(v,k) for k,v in a.iteritems()] 

the other example.

Read more about list comprehensions if you like, it’s very interesting what you can do with them.


回答 3

创建一个namedtuple列表

使用namedtuple通常很方便。例如,您有一个“名称”作为键,而“分数”作为值的字典,例如:

d = {'John':5, 'Alex':10, 'Richard': 7}

您可以将项目列为元组,根据需要进行排序,并获得名称和分数,比如说Python得分最高(index = 0)的玩家非常Python化,如下所示:

>>> player = best[0]

>>> player.name
        'Alex'
>>> player.score
         10

这该怎么做:

以随机顺序或保持collections.OrderedDict的顺序列出:

import collections
Player = collections.namedtuple('Player', 'name score')
players = list(Player(*item) for item in d.items())

按值(“分数”)排序:

import collections
Player = collections.namedtuple('Player', 'score name')

首先以最低分数排序:

worst = sorted(Player(v,k) for (k,v) in d.items())

首先以最高分排序:

best = sorted([Player(v,k) for (k,v) in d.items()], reverse=True)

Create a list of namedtuples

It can often be very handy to use namedtuple. For example, you have a dictionary of ‘name’ as keys and ‘score’ as values like:

d = {'John':5, 'Alex':10, 'Richard': 7}

You can list the items as tuples, sorted if you like, and get the name and score of, let’s say the player with the highest score (index=0) very Pythonically like this:

>>> player = best[0]

>>> player.name
        'Alex'
>>> player.score
         10

How to do this:

list in random order or keeping order of collections.OrderedDict:

import collections
Player = collections.namedtuple('Player', 'name score')
players = list(Player(*item) for item in d.items())

in order, sorted by value (‘score’):

import collections
Player = collections.namedtuple('Player', 'score name')

sorted with lowest score first:

worst = sorted(Player(v,k) for (k,v) in d.items())

sorted with highest score first:

best = sorted([Player(v,k) for (k,v) in d.items()], reverse=True)

回答 4

你想要的是dictitems()iteritems()方法。items返回(键,值)元组的列表。由于元组是不可变的,因此它们不能反转。因此,您必须迭代这些项并创建新的元组,以获取反转的(值,键)元组。对于迭代而言,iteritems是首选方法,因为它使用生成器来生成(键,值)元组,而不必将整个列表保留在内存中。

Python 2.5.1 (r251:54863, Jan 13 2009, 10:26:13) 
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> a = { 'a': 1, 'b': 2, 'c': 3 }
>>> a.items()
[('a', 1), ('c', 3), ('b', 2)]
>>> [(v,k) for (k,v) in a.iteritems()]
[(1, 'a'), (3, 'c'), (2, 'b')]
>>> 

What you want is dict‘s items() and iteritems() methods. items returns a list of (key,value) tuples. Since tuples are immutable, they can’t be reversed. Thus, you have to iterate the items and create new tuples to get the reversed (value,key) tuples. For iteration, iteritems is preferable since it uses a generator to produce the (key,value) tuples rather than having to keep the entire list in memory.

Python 2.5.1 (r251:54863, Jan 13 2009, 10:26:13) 
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> a = { 'a': 1, 'b': 2, 'c': 3 }
>>> a.items()
[('a', 1), ('c', 3), ('b', 2)]
>>> [(v,k) for (k,v) in a.iteritems()]
[(1, 'a'), (3, 'c'), (2, 'b')]
>>> 

回答 5

[(k,v) for (k,v) in d.iteritems()]

[(v,k) for (k,v) in d.iteritems()]
[(k,v) for (k,v) in d.iteritems()]

and

[(v,k) for (k,v) in d.iteritems()]

回答 6

这些是Python 3.x和Python 2.x的重大变化

对于Python3.x使用

dictlist = []
for key, value in dict.items():
    temp = [key,value]
    dictlist.append(temp)

对于Python 2.7使用

dictlist = []
for key, value in dict.iteritems():
    temp = [key,value]
    dictlist.append(temp)

These are the breaking changes from Python 3.x and Python 2.x

For Python3.x use

dictlist = []
for key, value in dict.items():
    temp = [key,value]
    dictlist.append(temp)

For Python 2.7 use

dictlist = []
for key, value in dict.iteritems():
    temp = [key,value]
    dictlist.append(temp)

回答 7

>>> a = {'a':1,'b':2,'c':3}

>>> [[x,a [x])for a.keys()中的x]
[('a',1),('c',3),('b',2)]

>>> [[(a [x],x)for a.keys()中的x]
[(1,'a'),(3,'c'),(2,'b')]
>>> a={ 'a': 1, 'b': 2, 'c': 3 }

>>> [(x,a[x]) for x in a.keys() ]
[('a', 1), ('c', 3), ('b', 2)]

>>> [(a[x],x) for x in a.keys() ]
[(1, 'a'), (3, 'c'), (2, 'b')]

回答 8

通过keys()values()字典的方法和zip

zip 将返回一个类似于有序字典的元组列表。

演示:

>>> d = { 'a': 1, 'b': 2, 'c': 3 }
>>> zip(d.keys(), d.values())
[('a', 1), ('c', 3), ('b', 2)]
>>> zip(d.values(), d.keys())
[(1, 'a'), (3, 'c'), (2, 'b')]

By keys() and values() methods of dictionary and zip.

zip will return a list of tuples which acts like an ordered dictionary.

Demo:

>>> d = { 'a': 1, 'b': 2, 'c': 3 }
>>> zip(d.keys(), d.values())
[('a', 1), ('c', 3), ('b', 2)]
>>> zip(d.values(), d.keys())
[(1, 'a'), (3, 'c'), (2, 'b')]

回答 9

d = {'John':5, 'Alex':10, 'Richard': 7}
list = []
for i in d:
   k = (i,d[i])
   list.append(k)

print list
d = {'John':5, 'Alex':10, 'Richard': 7}
list = []
for i in d:
   k = (i,d[i])
   list.append(k)

print list

回答 10

一个简单的是

list(dictionary.items())  # list of (key, value) tuples
list(zip(dictionary.values(), dictionary.keys()))  # list of (key, value) tuples

第二个不是更简单,而是。

A simpler one would be

list(dictionary.items())  # list of (key, value) tuples
list(zip(dictionary.values(), dictionary.keys()))  # list of (key, value) tuples

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。