Krio Krio - 6 days ago 5
Python Question

Make a dictionary of a csv file without imports

So I have a csv file of arbitrary amount of columns and rows (fully rectangular so no missing cells) of which I want to turn into a dictionary.

key1 key2 key3
1 2 3
4 5 6
7 8 9

I want to have a dictionary that will follow this pattern

{key1:[1,4,7], key2:[2,5,8], key3:[3,6,9]}

What I'm doing right now is reading each line. If I'm reading the first line each element becomes a key in the dictionary and maps to an empty list. Then I continue reading each line but here's where I run into the problem. I don't know how I assign the elements of each line to it's correct key (as dictionaries are random), that's assuming I know how to make generate a list of values that I can properly assign in the first place (for example, how can i make 1 go to key1, 2 go to key2 and 3 go to key3).

I want to do this all without imports. Let me know what you guys think.

>>> s = '''key1   key2   key3
1      2      3
4      5      6
7      8      9

>>> fields = s[0].split()
>>> rows = [[int(x) for x in line.split()] for line in s[1:]]
>>> print(dict(zip(fields, zip(*rows))))
{'key1': (1, 4, 7), 'key2': (2, 5, 8), 'key3': (3, 6, 9)}
  • s[0] is the first row of headings.
  • The .split() breaks the words into the field names
  • s[1:] gets the lines after the header row
  • line.split() splits the row into field values
  • int(x) converts the string entry "1" into the number 1
  • zip(*rows) transposes the list of rows
  • zip(fields, transposed_rows) makes a list of key/value pairs
  • dict(list_of_pairs) makes the dictionary

See references at: