0

I am reading a .dat file (supposed csv) to convert the data to json. Long story short I can't use source code from others cause the format of the data in the first half of the file is awkward and I needed to handle for that as well.

Now that I'm hitting the correct format for csv (one row of key's, and the following rows with values in the order of the keys) I am having a hard time putting them together. I get the keys just fine by splitting the line by (',') and by splitting, it stores in a list.

I can get the next line as well, by splitting and storing that line in a list.

Now comes the 2 questions.

  1. How do I match the value with the keys in the 2 lists? Ex.
List 1 = [Q1, Q2, Q3]
List 2 = [A1, A2, A3]

I want the result to look like

dict = {'Q1':'A1', 'Q2':'A2', 'Q3':'A3'}
  1. How do I handle multiple lines of values? Everything is in a loop so when it hits the second line of values, it just overwrites the previous answers
  • https://stackoverflow.com/questions/7271385/how-do-i-combine-two-lists-into-a-dictionary-in-python – JackofSpades Oct 30 '20 at 13:19
  • Yes I understand that there's a zip function. But my situation here is a little more complex. I actually don't know how many lines of "values" i'll have in the original data file to read, could be 1,2,10. So in my example above Q1 could hold A1, A2, A3 and so on. I'm not sure how to combine multiple lists – Suffertalon3 Oct 30 '20 at 13:27
  • You should edit your question to be more specific and include example code that is relevant to the question then. The zip function answers your question and solves the problem with the example code you provided. – JackofSpades Oct 30 '20 at 13:53
  • You use the zip function to combine multiple lists – JackofSpades Oct 30 '20 at 13:55
  • This is all explained in the second part of my question 2). – Suffertalon3 Oct 30 '20 at 14:25
  • You should show example code for your second question. If your overwriting values in a for loop, you're probably doing something wrong inside that for-loop. As for 'multiple lines of values' Does that mean a list that has values with newline characters? The newline characters won't affect using the `zip` function to merge lists of strings, even if they contain newline characters. – JackofSpades Oct 30 '20 at 14:37

1 Answers1

0

Use:

result = dict(zip(list_1, list_2))
Hamza
  • 5,373
  • 3
  • 28
  • 43