Let us Suppose, I have created 3 lists and I want to create a dictionary for it. e.g.
a= ['A', 'B', 'C', 'D']
b =[1, 2, 3, 4]
c = [9, 8, 7, 6]
Now What I want is to create a dictionary like this:
{'A':{'1' :'9'} , 'B':{'2':'8'}, 'C':{'3':'7'} , 'D':{'4':'6'}}
is it possible, Can Someone Help me on this?
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.
You can convert a Python list to a dictionary using the dict. fromkeys() method, a dictionary comprehension, or the zip() method. The zip() method is useful if you want to merge two lists into a dictionary.
In Python, a nested dictionary is a dictionary inside a dictionary. It's a collection of dictionaries into one single dictionary. Here, the nested_dict is a nested dictionary with the dictionary dictA and dictB . They are two dictionary each having own key and value.
To convert a list to dictionary, we can use list comprehension and make a key:value pair of consecutive elements. Finally, typecase the list to dict type.
You can create the dictionary from zip
-ed lists and convert the int values to strings - if I understood your question proper
dct = {x: {str(y): str(z)} for x, y, z in zip(a,b,c)}
Output:
{'A': {'1': '9'}, 'C': {'3': '7'}, 'B': {'2': '8'}, 'D': {'4': '6'}}
You can also use map()
here:
a = ['A', 'B', 'C', 'D']
b = [1, 2, 3, 4]
c = [9, 8, 7, 6]
dct = dict(map(lambda x, y, z : (x, {str(y): str(z)}), a, b, c))
print(dct)
Which outputs:
{'A': {'1': '9'}, 'B': {'2': '8'}, 'C': {'3': '7'}, 'D': {'4': '6'}}
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