[英]Is it possible to have nested dictionary using setdefault, appending to a list?
I would like to have a nested dictionary with a list of values that are attached to the sub-key. 我想要一个嵌套字典,其中包含附加到子键的值的列表。 Can't get the sub-key to recognise. 无法获取要识别的子密钥。
month = {}
for row in date:
month.setdefault(row[1],{row[0]: []})
month[row[0]].append(row[4])
print(month[main_key][sub_key])
I expect a list of values to be populated out through the appending method. 我希望通过附加方法填充值列表。 However, I keep getting a keyError. 但是,我一直收到keyError。
The desired output: 所需的输出:
{'row[1]': {'row[0]' :[row[4], row[4], row[4]],
'row[0]' :[row[4], row[4], row[4]]}}
Here's a simple example of what I think you are trying to achieve: 这是我想达到的简单示例:
>>> rows = [[1,2,3], [1,2,4], [1,3,3], [1,3,5], [2,3,9], [2,3,5]]
>>> ret = {}
>>> for row in rows:
... ret.setdefault(row[0], {}).setdefault(row[1], []).append(row[2])
...
>>> ret
{1: {2: [3, 4], 3: [3, 5]}, 2: {3: [9, 5]}}
How does it work? 它是如何工作的? For each row
: 对于每一row
:
row[0]
in ret
keys. 我们在ret
键中寻找row[0]
。 If it is not present, we add the pair (row[0], {})
to the dict, {}
being the nested dict. 如果不存在,则将对(row[0], {})
到字典, {}
是嵌套字典。 It it is present, we continue. 它存在,我们继续。 row[1]
is the key of the nested dict. 值row[1]
是嵌套字典的键。 We look for it in ret[row[0]]
(the first setdefault
return): if it is not present, we add an empty list. 我们在ret[row[0]]
(第一个setdefault
返回值)中寻找它:如果不存在,我们添加一个空列表。 row[2]
to the list ret[row[0]][row[1]]
我们将值row[2]
添加到列表ret[row[0]][row[1]]
Remember that: 请记住:
ret.setdefault(row[0], value_if_absent).func()
Means: 手段:
if row[0] not in ret:
ret[row[0]] = value_if_absent
ret[row[0]].func()
Usaully, value_if_absent
is a container and func
is one of append
, extend
, update
, ... methods. 通常, value_if_absent
是一个容器,而func
是append
, extend
, update
,...方法之一。 But func
may also be a setdefault
to create a new container if needed. 但是如果需要, func
可能也是setdefault
来创建一个新的容器。
Let's follow the statements in the block of the for-loop. 让我们关注for循环块中的语句。
The first is: 第一个是:
month.setdefault(row[1], {row[0]: []})
This will set a value of {row[0]: []}
( dictionary ) for the key row[1]
where the key hasn't been inserted in month
. 这将为尚未在month
插入密钥的row[1]
设置{row[0]: []}
( 字典 )的值。
The next statement is: 下一条语句是:
month[row[0]].append(row[4])
It appends row[4]
to a list retrieved from month
with the key row[0]
. 它将row[4]
附加到从month
检索的列表中,其中包含键row[0]
。 This line should error given that even when the key exists in month
, the value it is paired with is a dictionary and not a list. 考虑到即使键在month
存在,但与之配对的值也是字典而不是列表,因此该行应该出错。
That line should be written as: 该行应写为:
month[row[1]][row[0]].append(row[4])
month[row[1]]
retrieves the dictionary paired with key row[1]
which is then indexed to access the list paired with row[0]
. month[row[1]]
检索与键row[1]
配对的字典 ,然后对其进行索引以访问与row[0]
配对的列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.