1

Very similar to this previous question but not quite they same. In that example, the question is essentially how to perform some function on the values of the 'inner' dictionary - but the keys of both outer and inner dicts stay the same. I want the values of the inner dict to become they keys of the new dict, and the have new values based on the old keys.

I have a 'nested' dictionary like this:

data = {
    "A":{"X":1, "Y":2, "Z":3},
    "B":{"X":4, "Y":5, "Z":6},
    "C":{"X":7, "Y":8, "Z":9},
}

I want to create a new dictionary with the values of the inner dictionaries (i.e. the numbers) as the new keys, with new values based on concatenating the keys of the outer and inner dictionaries:

new_data = {
    1:"AX",
    2:"AY",
    3:"AZ",
    4:"BX",
    5:"BY",
    6:"BZ",
    7:"CX",
    8:"CY",
    9:"CZ",
}

Based on the linked post, I tried

data = {inner_v: outer_k + inner_k for inner_k, inner_v in outer_v.items() for outer_k, outer_v in outer_dict.items()}

But I get an error saying outer_v is not defined

MisterMiyagi
  • 44,374
  • 10
  • 104
  • 119
Nick
  • 162
  • 6
  • Loops inside a comprehension execute left to right, not right to left. Swap the two loops so that ``for outer_k, outer_v in outer_dict.items()`` is positioned and executes before ``for inner_k, inner_v in outer_v.items()``. – MisterMiyagi Jun 23 '20 at 17:51
  • 2
    Does this answer your question? [How to construct nested dictionary comprehension in Python with correct ordering?](https://stackoverflow.com/questions/20446526/how-to-construct-nested-dictionary-comprehension-in-python-with-correct-ordering) – Andras Deak -- Слава Україні Jun 23 '20 at 17:54
  • The order of nested `for` loops in a comprehension is the same as the order that you'd use in "traditional" `for` loops without a comprehension. – PM 2Ring Jun 23 '20 at 17:56

1 Answers1

1

When writing nested for loops in a comprehension, the nesting is happening left-to-right (and not viceversa).

Therefore, you just need to swap the order of the loops in the comprehension, with the understanding that outer_dict is actually data.

data = {
    "A":{"X":1, "Y":2, "Z":3},
    "B":{"X":4, "Y":5, "Z":6},
    "C":{"X":7, "Y":8, "Z":9},
}

outer_dict = data
new_data = {inner_v: outer_k + inner_k for outer_k, outer_v in outer_dict.items() for inner_k, inner_v in outer_v.items()}
print(new_data)
# {1: 'AX', 2: 'AY', 3: 'AZ', 4: 'BX', 5: 'BY', 6: 'BZ', 7: 'CX', 8: 'CY', 9: 'CZ'}
norok2
  • 25,683
  • 4
  • 73
  • 99