-1

I have a csv file that has the headers and the value lines are:

site,access_key,secret_access_key
sa1,something,something 
na1,something,something 

and so on. I would like the dictionary to look like

site_dict = {"sa1" :{"access_key" : "something", "secret_access_key" : "something"}, "na1" :{"access_key" : "something", "secret_access_key" : "something"}}

I tried what was suggested here : How to create a nested dictionary from a csv file with N rows in Python but it deals with numeric values and I could not get my head around changing it to string values. Any help would be appreciated. If you make a suggestion or provide an answer please make it an answer so I can mark it appropriately. EDIT: I changed the sa1 and na1 to keys by adding the quotes.

Andrew Madsen
  • 155
  • 1
  • 12

1 Answers1

0

You can use the csv module for reading and preread the first line to get the key-names:

# create data
with open("f.txt","w") as f:
    f.write("""site,access_key,secret_access_key
sa1,something111,something111 
na1,something222,something222""")

import csv

result = {}
with open("f.txt") as f:
    # get the keynames from the 1st line
    fields = next(f).strip().split(",")
    reader = csv.reader(f)
    # process all other lines
    for line in reader:
        # outer key is 1st value
        # inner key/values are from the header line and rest of line data
        result[line[0]] = dict(zip(fields[1:],line[1:]))

print(result)

Output:

{'sa1': {'access_key': 'something111', 'secret_access_key': 'something111'}, 
 'na1': {'access_key': 'something222', 'secret_access_key': 'something222'}}

Lookup: csv

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69