简体   繁体   English

Python字典中的Keyerror

[英]Keyerror in Python Dictionary

I am stack in something really simple, but I cannot find the right way. 我的想法很简单,但是找不到正确的方法。 I have a dictionary like this one: 我有一本这样的字典:

mydic= {'a': {'mylist':[..,..,..]}, 'b': {'mylist':[..,..,..]}}

I am trying to iterate through mylist and create a new subdictionary with the results of a function. 我试图遍历mylist并使用函数的结果创建一个新的子词典。

for i in mydic:
    for j in mydic[i]['mylist']:
         mydic[i]['thenewkey'][j] = myfunction(j)

The find dictionary would be like this: 查找字典将如下所示:

mydic= {'a': {'mylist':[..,..,..], 'thenewkey':{'..':'..', '..':'..'}}, 'b': {'mylist':[..,..,..],'thenewkey':{'..':'..', '..':'..'}}}

But when I run the code, I have a key error on thenewkey . 但是,当我运行代码时,我在thenewkeythenewkey键错误。 Any idea? 任何想法?

在分配给mydic[i]['thenewkey'][j]之前,您必须先创建mydic[i]['thenewkey'] mydic[i]['thenewkey'][j]

As already said, you have to create the thenewkey entry before you can add items to it, ie you'd have to add mydic[i]['thenewkey'] = {} to your outer loop. 如前所述,您必须先创建thenewkey条目,然后才能向其中添加项目,即必须将mydic[i]['thenewkey'] = {}到外部循环中。 You could use a defaultdict(dict) to make Python automatically insert missing entries, but since you have both list and dict entries, this does not seem like a good idea. 可以使用defaultdict(dict)来使Python自动插入丢失的条目,但是由于您同时具有listdict条目,所以这似乎不是一个好主意。

That said, using a dictionary comprehension makes it a bit shorter and IMHO much more readable: 就是说,使用字典理解会使它更短并且恕我直言更易读:

for i in mydic:
    mydic[i]['thenewkey'] = {j: myfunction(j) for j in mydic[i]['mylist']}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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