Skip to content Skip to sidebar Skip to footer

Read A File Into A Nested Dictionary?

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 How would I get it into a nested dictionary

Solution 1:

Here you go:

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

output = {}

for s inlines: 
    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 inpairs:
        day = pair[0].strip()
        output[first].setdefault(day, []).append(pair[1].strip())

    printoutput

The output looks like this:

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

Solution 2:

{'Tuesday': '15', '16'}

This does not seem valid so I'm going to assume you want {'Tuesday': ['15', '16']}

For each of the lists you'll have to do this:

newdict = {}
key = Nonefor item inlist:
    if key isNone:
        key = item
    else:
        if key notin newdict:
            newdict[key] = []
        newdict[key].append(item)
        key = None

I tested this on one of your lists and it worked.

Edit Output looks like this:

{'A': ['20'], 'Tuesday': ['15', '16'], 'Monday': ['14']}

Post a Comment for "Read A File Into A Nested Dictionary?"