Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the most efficient way to zip two nested list to a single level dictionary

for example:

list1=['k1','k2','k3',['k4','k5',['k6','k7']]]
list2=['v1','v2','v3',['v4','v5',['v6','v7']]]

and I want to merge them to a dictionary like this:

dict1={'k1':'v1','k2':'v2','k3':'v3','k4':'v4','k5':'v5','k6':'v6','k7':'v7'}

I have a way to do this, but I think it takes too much time:

def mergeToDict(keyList, valueList):
    resultDict = {}
    for key, value in itertools.izip(keyList, valueList):
        if type(key) == list and type(value) == list:
            resultDict=dict(resultDict,**mergeToDict(key, value))
        elif type(key) != list and type(key) != dict and type(key) != tuple:
            resultDict[key] = value
    return resultDict

Is there any better ideas?

like image 636
BackMountainBird Avatar asked Feb 14 '12 13:02

BackMountainBird


People also ask

How do I convert a nested list to a dictionary?

We can convert a nested list to a dictionary by using dictionary comprehension. It will iterate through the list. It will take the item at index 0 as key and index 1 as value.

How do you make a nested dictionary dynamically in Python?

To create a nested dictionary, simply pass dictionary key:value pair as keyword arguments to dict() Constructor. You can use dict() function along with the zip() function, to combine separate lists of keys and values obtained dynamically at runtime.

How do you zip a dictionary in python?

Python's zip() function is defined as zip(*iterables) . The function takes in iterables as arguments and returns an iterator. This iterator generates a series of tuples containing elements from each iterable. zip() can accept any type of iterable, such as files, lists, tuples, dictionaries, sets, and so on.

Can dictionary be nested to any depth?

Dictionaries can be nested to any depth. Dictionaries are mutable. Items are accessed by their position in a dictionary. All the keys in a dictionary must be of the same type.


1 Answers

I'd use some kind of flatten function:

def flatten(it):
    if isinstance(it, str):
        yield it
        return
    try:
        for x in it:
            for y in flatten(x):
                yield y
    except TypeError:
        yield it

Now you can do

from itertools import izip
my_dict = dict(izip(flatten(list1), flatten(list2)))

I think this way is more general and more transparent for the reader.

like image 122
Sven Marnach Avatar answered Oct 31 '22 23:10

Sven Marnach