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

How to convert list to dictionary in Python?

I have the following list

['BILL FROM:', 'TestCorp', 'USA, NY 02123, Washington St.', 'New York, NY, 02123', 'United States', 'musicjohnliofficial@gmail.com', 'BILL TO:', 'Yao Min', 'LA, 2123, Los Angeles', 'new York, NY, 9803432', 'United States', 'yao123@mail.com', 'INVOICE #', '01', 'INVOICE DATE', '2022-08-05', 'AMOUNT DUE', '$36.79', 'SUBTOTAL', '$36.74', 'TAX (0.13%)', '$0.05', 'TOTAL', '$36.79', 'Item', 'Description', 'Quantity', 'Unit Cost', 'Line Total', 'Pen', 'Pen, black coloe', '1.5', '$1.16', '$1.74', 'Book', 'Calculus, Zorych, pt. 1', '3.5', '$10.00', '$35.00', 'Powered by Shopify', 'www.shopify.com']

and I’m tryin to convert it to dictionary to get something like this:

{'Bill From:': 'TestCorp',...,'Powered by Shopify': 'www.shopify.com'}

So, every key in the dict should be i-th elemnt from my list, each value – i+1 element from the list. I’m trying to loop through that list taking each pair of it’s elements and put it into empty dict:

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

res_dct = {prepared_data[i]: prepared_data[i + 1] for i in range(, len(prepared_data))}

But I’m getting an error

IndexError: list index out of range

I have tried this code with smaller list and it worked!

>>> lst = ['a', 1, 'b', 2, 'c', 3]
>>> res_dct = {lst[i]: lst[i + 1] for i in range(0, len(lst), 2)}
>>> res_dct
{'a': 1, 'b': 2, 'c': 3}

So what’s wrong? If somebody has any ideas please help me figure that out. Thank you!

>Solution :

I think that your code is correct for lists that have an even number of elements, so they can be converted to dicts; but you get the error when it’s a list with odd number of elements, that cannot be converted to dict because an element is alone and cannot be paired to form a key-value pair.

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