Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 646
locklockM Avatar asked Apr 12 '26 14:04

locklockM


2 Answers

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.

like image 128
jpp Avatar answered Apr 15 '26 03:04

jpp


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)})
like image 42
Akash Swain Avatar answered Apr 15 '26 04:04

Akash Swain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!