locklockM
locklockM

Reputation: 139

Python create a specific dict from three list

I have three list, I want to convert into a specific dict

A = ["a", "b"]
B = ["10", "20"]
C = ["key1", "key2"]

I want a dict like that

"key1": {
  "name": "a",
  "age": 10
},
"key2": {
    "name": "b",
    "age": 20
  }

I try different way by different step, but I don't get this dict

for key in A:
  dict_A["name"].append(key)

Upvotes: 3

Views: 774

Answers (4)

Akash Swain
Akash Swain

Reputation: 520

If you don't want to use zip then you can use enumerate as given below:

print ({v:{"name": A[k],"age": B[k]} for k, v in enumerate(C)})

Upvotes: 1

ApprenticeHacker
ApprenticeHacker

Reputation: 22031

How about

for a,b,c in zip(A, B, C):
    your_dict[c] = {"name" : a, "age": b} 

Upvotes: 0

Ghilas BELHADJ
Ghilas BELHADJ

Reputation: 14106

In[1]:  {c: {'name': a, 'age': b} for a, b, c in zip(A, B, C)}
Out[1]: {'key1': {'name': 'a', 'age': '10'}, 'key2': {'name': 'b', 'age': '20'}}

Upvotes: 0

jpp
jpp

Reputation: 164773

Using a dictionary comprehension:

res = {key: {'name': name, 'age': age} for key, name, age in zip(C, A, B)}

This gives:

{'key1': {'age': '10', 'name': 'a'}, 'key2': {'age': '20', 'name': 'b'}}

zip allows you to aggregate elements from each iterable by index.

Upvotes: 7

Related Questions