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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With