【问题标题】:add element to a nested array in a dictionary converting series to readable dictionary with nested arrays python将元素添加到字典中的嵌套数组,将序列转换为具有嵌套数组的可读字典python
【发布时间】:2021-01-17 01:21:23
【问题描述】:

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

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' 

【问题讨论】:

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


    【解决方案1】:

    这行dataInfected9[index[1]].append(value) 不起作用的原因是它试图访问索引(例如'hr'),而它最初没有被声明或初始化。

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

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

    【讨论】:

    • 你的解释帮助我理解了另一个答案,你的很好,但另一个更干净
    • 好吧,如果有帮助那就太好了。继续努力
    【解决方案2】:

    使用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)
    

    【讨论】:

    • 谢谢!对我有用,不知道 dict.setdefault()
    猜你喜欢
    • 2013-12-07
    • 2017-01-20
    • 1970-01-01
    • 2022-06-14
    • 2018-02-16
    • 2019-12-28
    • 2022-12-05
    • 1970-01-01
    相关资源
    最近更新 更多