问题描述
我正在尝试使用列表将对象列表转换为字典
理解。
类似
entries = {}
[entries [int(d.date.strftime(''%m'')) )] = d.id]链接中的d]
当我尝试这样做时,我一直都会遇到错误。可能吗?请
字典对象有一个等同于[] .append的方法吗?也许一个
lambda?
感谢您的帮助!
Erik
Hi,
I''m trying to turn o list of objects into a dictionary using a list
comprehension.
Something like
entries = {}
[entries[int(d.date.strftime(''%m''))] = d.id] for d in links]
I keep getting errors when I try to do it. Is it possible? Do
dictionary objects have a method equivalent to [].append? Maybe a
lambda?
Thanks for your help!
Erik
推荐答案
试试...
[条目.__ setitem __(int(d.date.strftime(''%m''))],d.id)
链接]
顺便说一下......我也很好奇。我用''dir(dict)''找了一个
的方法,可以做我们想要的和宾果游戏!
~Sean
try...
[entries.__setitem__(int(d.date.strftime(''%m''))], d.id) for d in
links]
btw...I was curious of this too. I used ''dir(dict)'' and looked for a
method that might do what we wanted and bingo!
~Sean
通常是dict(whatEver)会做的;-)
示例:
a = [1,2 ,3,4,5,6,7,8,9,10]
aDict = dict(x中的[(x,x + 1),如果x%2 = = 0])
打印aDict
normally a dict(whatEver) will do ;-)
Example:
a = [1,2,3,4,5,6,7,8,9,10]
aDict = dict([(x,x+1) for x in a if x%2==0])
print aDict
entries = dict([(int(d.date.strftime(''%m'')),d.id)for d in links])
随着Python2.4及更高版本你可以使用生成器表达式
entries = dict((int(d.date.strftime(''%m'')),d。 id)for d in links)
问候,
Pierre
entries = dict([ (int(d.date.strftime(''%m'')),d.id) for d in links] )
With Python2.4 and above you can use a "generator expression"
entries = dict( (int(d.date.strftime(''%m'')),d.id) for d in links )
Regards,
Pierre
这篇关于python可以从列表理解中创建一个字典吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!