所以我有类似
的东西retval = {}
# ...
# some code here to fetch data
# ...
for row in cursor.fetchall():
if row.someid not in retval:
retval[row.someid] = [dict(zip(columns,rows))]
else:
retval[row.someid].append(dict(zip(columns,rows))
产生:
retval = {
1: [{'someid': 1, 'samplefield': 'valueX', ... },
{'someid': 1, 'samplefield': 'valueY', ... }],
2: [{'someid': 2, 'samplefield': 'valueX', ... }]
}
我觉得有更多的pythonic方式来达到我需要的结果。
确切地说,有没有办法减少这些代码行:
if row.someid not in retval:
retval[row.someid] = [dict(zip(columns,rows))]
else:
retval[row.someid].append(dict(zip(columns,rows))
是一行吗?
答案: 一直在docs!感谢Christian Ternus& chthonicdaemon让我指向正确的方向。我更新了这个原因,我发现根据文档可以有多种方法。
from collections import defaultdict
retval = defaultdict(list) ## Or retval = defaultdict(lambda: []) based on my accepted answer.
# ...
# some code here to fetch data
# ...
for row in cursor.fetchall():
retval[row.someid].append(dict(zip(columns,rows))
或
retval = {}
# ...
# some code here to fetch data
# ...
for row in cursor.fetchall():
retval.setdefault(row.someid, []).append(dict(zip(columns,rows))
希望这对你有所帮助,就像它帮助了我一样!
答案 0 :(得分:3)
尝试使用内置defaultdict
模块中的collections
:
from collections import defaultdict
retval = defaultdict(lambda: [])
# ...
# some code here to fetch data
# ...
for row in cursor.fetchall():
retval[row.someid].append(dict(zip(columns,rows))