[英]How to get a list containing the values and the keys of a dictionary?
I am trying to understand what's the most efficient way for producing a list containing the values and the keys of a dictionary.我试图了解生成包含字典的值和键的列表的最有效方法是什么。 I've tried using
.items()
function but with poor results because items()
returns a list of tuples that then I have to flatten importing other modules.我试过使用
.items()
function 但结果很差,因为items()
返回一个元组列表,然后我必须展平导入其他模块。 At the moment I am using:目前我正在使用:
zdict = { 'a':1,'b':2,'c':3}
mylistofvaluesandkeys = list(zdict) + list(zdict.keys()))
The result I am looking is a list eg [1, 2, 3, 'a', 'b', 'c']
where I've all the elements in any order.我正在寻找的结果是一个列表,例如
[1, 2, 3, 'a', 'b', 'c']
,其中所有元素都按任意顺序排列。
Is there a better way to perform this task?有没有更好的方法来执行此任务?
You can do it lazily with itertools
:您可以使用
itertools
懒惰地做到这一点:
>>> import itertools
>>> itertools.chain(zdict.values(), zdict.keys())
<itertools.chain object at 0x10a25a9d0>
>>> list(itertools.chain(zdict.values(), zdict.keys()))
[1, 2, 3, 'a', 'b', 'c']
If it is acceptable to have keys mixed with values you can simply do this:如果可以接受将键与值混合,您可以简单地执行以下操作:
from itertools import chain
list(chain(*zdict.items()))
This is the result:这是结果:
['a', 1, 'b', 2, 'c', 3]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.