skip to Main Content

I have the following list

['BILL FROM:', 'TestCorp', 'USA, NY 02123, Washington St.', 'New York, NY, 02123', 'United States', '[email protected]', 'BILL TO:', 'Yao Min', 'LA, 2123, Los Angeles', 'new York, NY, 9803432', 'United States', '[email protected]', '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:

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!

2

Answers


  1. You can do with zip,

    dict(zip(lst[::2], lst[1::2]))
    

    Using islice,

    from itertools import islice
    dict(zip(islice(lst, 0, None, 2), islice(lst, 1, None, 2)))
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search