【问题标题】:Appending key, values to a nested dictionary in Python将键、值附加到 Python 中的嵌套字典
【发布时间】:2020-07-31 14:43:41
【问题描述】:

我在 CSV 中有一些数据,示例摘录如下,我想将此数据添加到嵌套字典中。

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

问题: 我遇到的问题是只存储最后一个键值,我希望将它们全部包含在内。我对 Python 还很陌生,我知道为什么会出现问题,但无法递增和附加所有键值。

目前的最终结果如下:

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

我需要的最终结果:

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?'}

代码:

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)

如果能提供任何帮助,我将不胜感激。

【问题讨论】:

  • 为什么Precodesdict?您将其用作列表,只需将其设为列表即可。

标签: python csv dictionary nested


【解决方案1】:

这是一种方法,使用内置 collections 包中的 defaultdict

首先,导入包并设置数据:

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+
'''

其次,遍历数据。默认字典的值是字典。 (这使我们能够创建字典字典,而无需检查字典是否存在,必要时创建它。)

dd = defaultdict(dict)

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

它是这样的:

dd

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

【讨论】:

  • 这让我更接近目标,但我需要最终的解决方案看起来像这样:
猜你喜欢
  • 1970-01-01
  • 2018-06-27
  • 1970-01-01
  • 1970-01-01
  • 2019-02-11
  • 2019-09-20
  • 2021-08-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多