简体   繁体   中英

Appending key, values to a nested dictionary in Python

I have some data in a CSV and example extract is below, I'd like to add this data to a nested dictionary.

Qgen 1 Male
Qgen 2 Female
Qageband 1 18-24
Qageband 2 25-34
Qageband 3 35+

Issue: The issue I have is only the last key value is stored, I want all of them to be included. I'm fairly new to Python and I know why the issue occurs but have not been able to increment and append all the key values.

Current end result is below:

ExampleDict = {'Qgen': {'Precodes':{'2':'Male'}, 'qtext':'What is your gender?'},
               'Qageband': {'Precodes':{'3':'35+'}, 'qtext':'How old are you?'}

End result I require:

ExampleDict = {'Qgen': {'Precodes':{'1':'Male', '2':'Male'}, 'qtext':'What is your gender?'},
               'Qageband': {'Precodes':{'1':'18-24', '2':'25-34', '3':'35+'}, 'qtext':'How old are you?'}

Code:

import csv
####### READ IN PRECODES ###########
f=open('LabelsImport_ShortVersion.csv','r')
reader = csv.reader(f)

ExampleDict = {}

ListOfVars=['Qgen','Qageband ']

for row in reader:
    if key in ListOfVars:
        ExampleDict[row[0]]['Precodes']={}
        ExampleDict[row[0]]['Precodes'].update({row[1]:row[2]})
print (ExampleDict)

I'd appreciate any assistance offered.

Here is one way, using defaultdict from the built-in collections package:

First, import packages and set up the data:

from collections import defaultdict
from io import StringIO

data = '''Qgen 1 Male
Qgen 2 Female
Qageband 1 18-24
Qageband 2 25-34
Qageband 3 35+
'''

Second, iterate over the data. The default dict has values that are, well, dictionaries. (This enables us to create a dictionary of dictionaries, without checking to see if dict exists, creating it if necessary.)

dd = defaultdict(dict)

for line in StringIO(data):
    key_1, key_2, val = line.rstrip('\n').split(' ')
    dd[key_1][key_2] = val

Here's what it looks like:

dd

defaultdict(dict,
            {'Qgen': {'1': 'Male', '2': 'Female'},
             'Qageband': {'1': '18-24', '2': '25-34', '3': '35+'}})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM