来自Python中的dict的元组列表

Man*_*áoz 41 python dictionary list key-value

如何从Python中的dict获取键值元组列表?

And*_*ton 72

仅适用于Python 2.x(感谢Alex):

yourdict = {}
# ...
items = yourdict.items()
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅http://docs.python.org/library/stdtypes.html#dict.items.

仅适用于Python 3.x(取自Alex的答案):

yourdict = {}
# ...
items = list(yourdict.items())
Run Code Online (Sandbox Code Playgroud)


Tri*_*ych 9

有关元组的列表:

my_dict.items()
Run Code Online (Sandbox Code Playgroud)

但是,如果你所做的只是迭代这些项目,那么通常最好使用dict.iteritems(),这样可以提高内存效率,因为它一次只返回一个项目,而不是一次只返回所有项目:

for key,value in my_dict.iteritems():
     #do stuff
Run Code Online (Sandbox Code Playgroud)


小智 6

在Python中,从dict到的转换list非常容易。三个例子:

d = {'a': 'Arthur', 'b': 'Belling'}

d.items() [('a', 'Arthur'), ('b', 'Belling')]

d.keys() ['a', 'b']

d.values() ['Arthur', 'Belling']
Run Code Online (Sandbox Code Playgroud)

如上一个答案“ 将Python词典转换为List”所示


Ale*_*lli 5

在Python 2.*thedict.items(),如@ Andrew的答案.在Python中3.*,list(thedict.items())(因为items只有一个可迭代的视图,而不是一个列表,list如果你需要一个列表,你需要明确地调用它).

  • 安德鲁,我认为这个选择只反映了迭代器大多数时候都是你想要的. (3认同)
  • @Andrew,benhoyt是对的 - 绝大多数用途只是循环,并且在极少数情况下明确地制作一个列表,你确实需要一个列表,毕竟是一个非常Pythonic的方法! - ) (2认同)