0

I have a defaultdict dictionary, such as:

defaultdict = {
           key1: [[objn],[obj0,...objn-1],
           key2: [[objm, objm-1],[obj0,...ombjm-2]]
         }

This list is created using:

result = collections.defaultdict(list)
for k, vs in groupby(
                qs, attrgetter("attr1", "attr2")
            ):
                result[k].append(list(vs))

This is why I have my final dict with a list of lists, I was wondering what would be the most efficient way to combine those lists for each key-value pair?

I can loop over the dictionary and use:

for k in result:
    result[k] = list(itertools.chain.from_iterable(result[k]))

Is there a more efficient way to do this in a single loop when creating the result dictionary

ashes999
  • 1,234
  • 1
  • 12
  • 36
  • 2
    Does this answer your question? [What is the syntax to insert one list into another list in python?](https://stackoverflow.com/questions/3748063/what-is-the-syntax-to-insert-one-list-into-another-list-in-python) Extend your list instead of appending to it in your first loop – Pranav Hosangadi Feb 01 '21 at 16:48
  • Yes thanks, i didn't think of `extend` in this context, seems to be the best way! – ashes999 Feb 01 '21 at 16:52

0 Answers0