此代码的更“pythonic”版本是什么? (在Python 2.x中)
from collections import defaultdict
dd = defaultdict(list)
for i in some_list_of_items:
current_dict = dict_from_an_item(i)
for (k, v) in current_dict.items():
dd[k].extend(v)
dict_from_an_item
解析一个项目并返回一个不包含嵌套列表的dict作为值。像这样:
{ 'key1': [1, 2, 3],
'key2': [2, 3, 4],
'key3': [3, 4, 5, 6, 7, 8]}
答案 0 :(得分:3)
您可以省略current_dict
变量。同样k, v
比(k, v)
from collections import defaultdict
dd = defaultdict(list)
for i in some_list_of_items:
for k, v in dict_from_an_item(i).iteritems():
dd[k].extend(v)
答案 1 :(得分:0)
如果您出于性能原因不需要defaultdict
,则可以执行以下操作:
d = {k:v for i in some_list_of_items for k, v in dict_from_an_item(i).iteritems()}