Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

python: I want to make a dictionary using two, two dimensional lists

I want to make a single list with two dictionaries in it using two, two dimensional lists. Note that each element should have to be paired to the element of the second list.

a = [[1,2,3],[4,5,6]]
b = [[7,8,9],[10,11,12]]
c = dict(zip(a,b))

is not working because list is not hash-able.
Then I need the out put as

 c = [{1:7, 2:8, 3:9}, {4:10, 5:11, 6:12}]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You want something like the following:

c = [dict(zip(keys, vals)) for keys, vals in zip(a, b)]

Here we use a list comprehension to zip and cast to a dict for each inner list in the original lists a and b.

Alternatively, we could flatten out the comprehension further, to get:

c = [{k: v for k, v in zip(keys, vals)} for keys, vals in zip(a, b)]

Both are equivalent, its just a matter of style.

Output:

>>> print(c)
[{1: 7, 2: 8, 3: 9}, {4: 10, 5: 11, 6: 12}]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading