Reputation: 379
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.
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
. Any idea?
Upvotes: 1
Views: 422
Reputation: 82899
As already said, you have to create the thenewkey
entry before you can add items to it, i.e. you'd have to add mydic[i]['thenewkey'] = {}
to your outer loop. 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.
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']}
Upvotes: 1
Reputation: 32429
You have to create first mydic[i]['thenewkey']
before assigning to mydic[i]['thenewkey'][j]
.
Upvotes: 3