[英]convert a dict to a list of lists
I've got a defaultdict that looks like... 我有一个defaultdict看起来像...
defaultdict(int,
{" u'CAMILLE'": 10,
" u'SAHARA'": 1,
" u'JEREMIAH'": 114,
" u'EDISON'": 9,
...}
I need something like... 我需要类似...
[[u'CAMILLE', 10],
[u'SAHARA', 1],
[u'JEREMIAH',114],
[u'EDISON', 9],
...]
both 都
firstnames = [lambda x,y:list(x,y) for k,v in firstnames.items()]
and 和
firstnames = [lambda x,y:[x,y] for k,v in firstnames.items()]
produce 生产
[<function __main__.<lambda>>,
<function __main__.<lambda>>,
<function __main__.<lambda>>,
<function __main__.<lambda>>,
...]
which is obviously not what I'm intending. 这显然不是我想要的。 How can I correct this code?
如何更正此代码?
There is no need to use lambda
s: 无需使用
lambda
:
firstnames = [[k,v] for k,v in firstnames.items()]
or even shorter: 甚至更短:
firstnames = [list(t) for t in firstnames.items()]
lambda
creates an anonymous function. lambda
创建一个匿名函数。 This means you have generated a list of functions that take as input two parameters (here x
and y
) and return a list [x,y]
. 这意味着您已经生成了一个函数列表,该函数将两个参数(此处为
x
和y
)作为输入并返回列表[x,y]
。 The k
and v
are not even taken into account in your approach. 您的方法中甚至没有考虑
k
和v
。
Using map will also work: 使用地图也可以:
firstnames = map(list, firstnames.items())
Note that in python3 this will build a generator (so, as Willem comment says, its better to inmediatly use list()
around the map call so the values are taken at the call moment). 请注意,在python3中,这将构建一个生成器(因此,如Willem评论所言,最好在map调用周围直接使用
list()
,以便在调用时获取值)。
firstnames = list(map(list, firstnames.items()))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.