1

I am trying to "flatten" a dictionary that looks like this:

d = {
    "USA": ["US", "United States"],
    "SGP": ["JP", "Japan", "Singapore"]
}

The format I would like to get it into is this:

new_d = {
    "United States": "USA",
    "US": "USA",
    "JP": "SGP",
    "Japan": "SGP",
    "Singapore": "SGP"
}
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
iiphiizy
  • 39
  • 3

1 Answers1

5

Use a dictionary comprehension with nested iteration:

>>> d = {
...     "USA": ["US", "United States"],
...     "SGP": ["JP", "Japan", "Singapore"]
... }
>>> {i: k for k, v in d.items() for i in v}
{'US': 'USA', 'United States': 'USA', 'JP': 'SGP', 'Japan': 'SGP', 'Singapore': 'SGP'}
  • k, v in d.items() -> k = "USA", ..., v = ["US", "United States"], ...
  • i in v -> i = "US", ...

hence:

  • {i: k ...} -> {"US": "USA", ...}
Samwise
  • 68,105
  • 3
  • 30
  • 44