从只有文本的文件中创建嵌套字典

时间:2019-06-02 20:04:36

标签: python python-3.x

我有一个带有标头的csv文件,其值行是:

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

,依此类推。我希望字典看起来像

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

我尝试了这里建议的方法:How to create a nested dictionary from a csv file with N rows in Python,但是它处理的是数字值,我无法直截了当地将其更改为字符串值。任何帮助,将不胜感激。如果您有任何建议或答案,请给我一个答案,以便我们适当标记。编辑:我通过添加引号将sa1和na1更改为键。

1 个答案:

答案 0 :(得分:0)

您可以使用csv模块来读取和预读第一行以获取键名:

# 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)

输出:

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

查找:csv