What is a more "pythonic" version of this code? (in 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)
the dict_from_an_item
parses an item and returns a dict that contains not nested lists as the values. Something like this :
{ 'key1': [开发者_JAVA技巧1, 2, 3],
'key2': [2, 3, 4],
'key3': [3, 4, 5, 6, 7, 8]}
You could spare the current_dict
variable. Also k, v
is more pythonic than (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)
if you don't need a defaultdict
for performance reasons you could do:
d = {k:v for i in some_list_of_items for k, v in dict_from_an_item(i).iteritems()}
精彩评论