Search code examples
pythonpython-itertools

itertools.izip() for not predefined count of lists


I have the following data structure: {'one':['a','b','c'],'two':['q','w','e'],'three':['t','u','y'],...}. So, the dictionary has variant count of keys. Each array, picked by dict's key has similar length. How I can convert this structure to following: [{'one':'a','two':'q','three':'t'},{'one':'b','two':'w','three':'y'},...]?

I think I should use itertools.izip(), but how i can apply it with not predefined count of args? Maybe something like this: itertools.izip([data[l] for l in data.keys()])?

TIA!


Solution

  • Your assessment in using izip is correct but the way of using it is not quite right

    You first need to

    • get the items as a list of tuples (key, value), (using iteritems() method if using Py2.x or items() if using Py3.x)
    • create a scalar product of key and value
    • flatten the list (using itertools.chain)
    • zip it (using itertools.izip)
    • and then create a dict of each element

    Here is the sample code

    >>> from pprint import PrettyPrinter
    >>> pp = PrettyPrinter(indent = 4)
    >>> pp.pprint(map(dict, izip(*chain((product([k], v) for k, v in data.items())))))
    [   {   'one': 'a', 'three': 't', 'two': 'q'},
        {   'one': 'b', 'three': 'u', 'two': 'w'},
        {   'one': 'c', 'three': 'y', 'two': 'e'}]
    >>>