{inner_k: myfunc(inner_v)} isn't a dictionary comprehension. It's just a dictionary.
You're probably looking for something like this instead:
data = {outer_k: {inner_k: myfunc(inner_v) for inner_k, inner_v in outer_v.items()} for outer_k, outer_v in outer_dict.items()}
For the sake of readability, don't nest dictionary comprehensions and list comprehensions too much.
Answer from Blender on Stack Overflow{inner_k: myfunc(inner_v)} isn't a dictionary comprehension. It's just a dictionary.
You're probably looking for something like this instead:
data = {outer_k: {inner_k: myfunc(inner_v) for inner_k, inner_v in outer_v.items()} for outer_k, outer_v in outer_dict.items()}
For the sake of readability, don't nest dictionary comprehensions and list comprehensions too much.
Adding some line-breaks and indentation:
data = {
outer_k: {inner_k: myfunc(inner_v)}
for outer_k, outer_v in outer_dict.items()
for inner_k, inner_v in outer_v.items()
}
... makes it obvious that you actually have a single, "2-dimensional" dict comprehension. What you actually want is probably:
data = {
outer_k: {
inner_k: myfunc(inner_v)
for inner_k, inner_v in outer_v.items()
}
for outer_k, outer_v in outer_dict.items()
}
(which is exactly what Blender suggested in his answer, with added whitespace).
Dict unpacking in dict comprehensions
Nested Dictionary Comprehension
Bonus question: am I wasting my time even trying to do this, since the nested for loop works fine?
More on reddit.comAt what point are loops better than list comprehensions?
Nested Dictionary Comprehension From Dataframe?
I am trying to do a nested dict. comprehension, but running into a syntaxerror.
What I want to do is remove the spaces in my lists. Sorry about the syntax, I had to space it all manually here, it's normal in my code:
email_dict=
{'New ID':
{'Fwd: RES': ['3', ' ', '4', ' ', '5'],
'RES CON': ['2', ' ', '1', '2'],
'RES EXP': [],
'RES SOLD': ['6', ' ', '1', '3']}
}I tried to use this code to loop through each key, and find only the digits / remove the empty spots:
email_dict["New ID"] = {key for key in email_dict["New ID"]:[id for id in email_dict["New ID"][key] if id.isdigit()]}I think I am really close, but not getting something here.
I can make it work when done this way:
for key in email_dict["New ID"]: temp_key = [] for id in email_dict["New ID"][key]: if id.isdigit(): temp_key += id email_dict["New ID"][key] = temp_key
But I'd prefer to learn how to do it a lot cleaner, and without the extra variable.