在字典中的嵌套数组中添加元素,将序列转换为带有嵌套数组的可读字典python

时间:2020-10-01 10:17:47

标签: python arrays python-3.x pandas dictionary

我需要向字典中的数组添加元素,这是我的代码:

indexes9 = []
dataInfected9 = {}
for index, value in data9.items():
    if index[0] not in indexes9:
        indexes9.append(index[0])
    dataInfected9[index[1]].append(value)

数据看起来像这样

{Series(32,)}
(('NSW', 'hs'), 1539) (('NSW', 'blood'), 70) (('NSW', 'hsid'), 50) .... (('QLD', 'hs'), 186)

应该看起来像这样:

dataInfected9 = {
    "hs":[1539, ..., 186],
    "blood":[70, ..., 90],
    ....
    }, 
    
)
indexes=['NSW', ..., 'QLD']

问题是此代码dataInfected9[index[1]].append(value)无法正常工作,是我的错误吗?

File ... line 84... 
dataInfected9[index[1]].append(value)
KeyError: 'hs' 

2 个答案:

答案 0 :(得分:1)

使用dict.setdefault

例如:

dataInfected9 = {}
indexes = set()                     #Using set to prevent dups.
for (k, v), n in data9.items():
    indexes.add(k)
    dataInfected9.setdefault(v, []).append(n)

答案 1 :(得分:1)

此行dataInfected9[index[1]].append(value)不起作用的原因是,它在最初未声明或初始化时尝试访问索引(例如'hr')。

下面的解决方案是,在有问题的行之前添加以下内容:

if index[1] not in dataInfected9:
    dataInfected9[index[1]] = []