esenes221
esenes221

Reputation: 27

how can i map one list with keys and others lists with values into a dictionary

I want to make a dictionary which contains sub-dictionaries

K = ['k1', 'k2', 'k3']  # key list
A = [['v1', 'v2', 'v3'], ['1', '2', '3']]  #value list
list_dict = ['dict1', 'dict2']
D = {d : {} for d in list_dict}

I want to do this:

D = {'dict1': {'k1': 'v1',
               'k2': 'v2',
               'k3': 'v3'},
     'dict2': {'k1': '1',
               'k2': '2',
               'k3': '3'}}

Upvotes: 0

Views: 122

Answers (4)

inspectorG4dget
inspectorG4dget

Reputation: 113965

In [70]: D = {d : dict(zip(K,v)) for d,v in zip(list_dict, A)}

In [71]: D
Out[71]: 
{'dict1': {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'},
 'dict2': {'k1': '1', 'k2': '2', 'k3': '3'}}

Upvotes: 1

brodeur
brodeur

Reputation: 96

Another method.

d = dict.fromkeys(list_dict)
for i, k in enumerate(sorted(d.keys())) :
    d[k] = {key:value for key, value in zip(K, A[i])}

Upvotes: 0

Nicolas M.
Nicolas M.

Reputation: 1478

You can mix zip function with a dict as follow:

K = ['k1', 'k2', 'k3']  # key list
A = [['v1', 'v2', 'v3'], ['1', '2', '3']]  # value list
list_dict = ['dict1', 'dict2']
D = {}

for i in range(len(A)):
    D[list_dict[i]] = (dict(zip(K, A[i])))

print(D)

NB : it's very similar to : Map two lists into a dictionary in Python

Upvotes: 0

Wso
Wso

Reputation: 302

Try using:

answer = {list_dict[l]: {K[i]: A[l][i] for i in range(len(K))} for l in range(len(list_dict))}

This sets answer to a dictionary where the keys are all the items in list_dict. The values are then dictionaries generated by using every item in K mapped to the corresponding item in A[l] where l is the number of the key in list_dict.

answer is:

{
'dict1': 
    {'k3': 'v3',
     'k2': 'v2',
     'k1': 'v1'},
'dict2': 
    {'k3': '3',
     'k2': '2',
     'k1': '1'}
}

Hope this helps.

Upvotes: 0

Related Questions