【问题标题】:Creating a nested dictionary from file that has only text从只有文本的文件创建嵌套字典
【发布时间】:2019-06-02 20:04:36
【问题描述】:

我有一个 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 更改为键。

【问题讨论】:

标签: python python-3.x


【解决方案1】:

您可以使用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

【讨论】:

  • 非常感谢!这比我链接到的帖子中建议的要优雅得多。
猜你喜欢
  • 2021-06-21
  • 2018-05-14
  • 1970-01-01
  • 2020-12-15
  • 2017-07-25
  • 1970-01-01
  • 1970-01-01
  • 2016-05-06
  • 2021-06-22
相关资源
最近更新 更多