2

I am trying to read from a csv file and store the data in a nested dictionary.

CSV file content

Type, ID, Frequency
Advanced,AAA,30 secs
Advanced,AAA,60 secs
Advanced,BBB,30 secs
Basic,CCC,30 secs
Basic,CCC,60 secs
Basic,DDD,30 secs

Expected output where the 'type' is the higher level key with the values as another dictionary with the ID and frequency as the key/value pair.

{'Advanced': {'AAA':['30 secs', '60 secs'], 'BBB':['30 secs']}, 'Basic': {'CCC':['30 secs', '60 secs'], 'DDD':['30 secs']}}

With two columns I got it to work using a defaultdict container.

symbols = co.defaultdict(list)
with open(filename, 'r') as f:
    lines = csv.DictReader(f)
    for line in lines:
        print(line)
        symbols[line['Type']].append(line['ID'])

1 Answer 1

2

You can use dict.setdefault instead:

symbols = {}
with open(filename, 'r') as f:
    for row in csv.DictReader(f, skipinitialspace=True):
        symbols.setdefault(row['Type'], {}).setdefault(row['ID'], []).append(row['Frequency'])

symbols becomes:

{'Advanced': {'AAA': ['30 secs', '60 secs'], 'BBB': ['30 secs']}, 'Basic': {'CCC': ['30 secs', '60 secs'], 'DDD': ['30 secs']}}

Or if you prefer to use collections.defaultdict, you should make symbols a defaultdict of defaultdict of lists instead:

symbols = defaultdict(lambda: defaultdict(list))
for row in csv.DictReader(f, skipinitialspace=True):
    symbols[row['Type']][row['ID']].append(row['Frequency'])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.