python - Is it possible to combine a dictionary of lists together into one list? -


say have dictionary so:

my_list = {     "foo": ["a", "b", "c"],     "bar": ["d", "e", "f"] } 

how combine lists in dictionary 1 large list in 1 line of code (meaning there not temporary variable)? came following solution, not elegant:

def combine_list_dictionary():     temp = []     (key, value_list) in my_list:         temp += value_list     return temp  combine_list_dictionary()  # ["a", "b", "c", "d", "e", "f"] 

i don't mind keys lost in process.

don't use sum join lists. there long discussion on python ideas mailing list around why bad idea (will link later).

itertools.chain solution, or if rather go functional then

>>> my_list = { ...     "foo": ["a", "b", "c"], ...     "bar": ["d", "e", "f"] ... } >>> import operator op >>> reduce(op.concat, my_list.values()) ['a', 'b', 'c', 'd', 'e', 'f'] >>> 

here performance comparison between chain , reduce both small , large dictionaries.

>>> import random >>> dict_of_lists = {k: range(random.randint(0, k)) k in range(0, random.randint(0, 9))} >>> %timeit list(itertools.chain.from_iterable(my_list.values())) slowest run took 12.72 times longer fastest. mean intermediate result being cached 1000000 loops, best of 3: 995 ns per loop >>> %timeit reduce(op.concat, my_list.values()) slowest run took 19.77 times longer fastest. mean intermediate result being cached 1000000 loops, best of 3: 467 ns per loop 

reduce twice fast itertools. true larger structures.

>>> dict_of_lists = {k: range(random.randint(0, k)) k in range(0, random.randint(0, 9999))} >>> %timeit list(itertools.chain.from_iterable(my_list.values())) slowest run took 6.47 times longer fastest. mean intermediate result being cached 1000000 loops, best of 3: 1 µs per loop >>> %timeit reduce(op.concat, my_list.values()) slowest run took 13.68 times longer fastest. mean intermediate result being cached 1000000 loops, best of 3: 425 ns per loop 

Comments

Popular posts from this blog

sequelize.js - Sequelize group by with association includes id -

android - Robolectric "INTERNET permission is required" -

java - Android raising EPERM (Operation not permitted) when attempting to send UDP packet after network connection -