将文件读到嵌套字典中? [英] Read a file into a nested dictionary?

查看:69
本文介绍了将文件读到嵌套字典中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个像这样保存任意值的简单文件:

Say I have a simple file like so holding arbitrary values:

A, 20, Monday, 14, Tuesday, 15, Tuesday, 16
B, 40, Wednesday, 14, Friday, 12

我将其放入嵌套字典中,以便每个k / v对都像这样:

How would I get it into a nested dictionary so that each k/v pair looks like:

{'A': {'A':'20', 'Monday': '14', 'Tuesday': ['15', '16']},
'B': {'B':'40', 'Wednesday': '14', 'Friday': '12'}}

(如果由于 A'和'B'两次作为键出现,它们的第二次出现是否用其他键代替都没关系。)

(If a key error arises from having 'A' and 'B' appear as keys twice, it doesn't matter if the second occurrence of each is replaced with something else.)

我对嵌套字典的了解是太好了,所以我能得到的最远的结果是将行读入列表中,并将整个列表存储为一个值,其中键为第一行元素。

My knowledge of nested dictionaries isn't great, so the furthest I've been able to get is reading the lines into a list and having the whole list stored as a value with the key being the first line element.

d = {}
with open (filename) as f:
    content = f.readlines()
    for line in content:
        line = line.strip('\r').strip('\n').split(',')
        d[line[0]] = line

返回输出

{'A': ['A', '20', 'Monday', '14', 'Tuesday', '15', 'Tuesday', '16'], 'B': 
['B', '40', 'Wednesday', '14', 'Friday', '12']}


推荐答案

您在这里:

with open(filename) as f:
   lines = f.readlines()

output = {}

for s in lines: 
    split_line = s.split(",")
    first = split_line[0].strip()
    output[first] = {}
    output[first][first] = split_line[1].strip()
    pairs = []
    for i in range(0, len(split_line[2:]), 2):
        pairs.append(split_line[2:][i:i+2])

    for pair in pairs:
        day = pair[0].strip()
        output[first].setdefault(day, []).append(pair[1].strip())

    print output

输出看起来像这样:

{'A': {'A': '20', 'Tuesday': ['15', '16'], 'Monday': ['14']}, 'B': {'B': '40', 'Friday': ['12'], 'Wednesday': ['14']}}

这篇关于将文件读到嵌套字典中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆