Pythonic更新`defaultdict`

时间:2011-03-15 12:25:23

标签: python

此代码的更“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]}

2 个答案:

答案 0 :(得分:3)

您可以省略current_dict变量。同样k, v(k, v)

更pythonic
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()}