Search code examples
pythonpython-3.xdictionarypython-3.7

How can I flatten a dictionary with a list for values?


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"
}

Solution

  • 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", ...}