我正在尝试"压平";一本看起来像这样的字典:
d = {
"USA": ["US", "United States"],
"SGP": ["JP", "Japan", "Singapore"]
}
我想把它变成这样的格式:
new_d = {
"United States": "USA",
"US": "USA",
"JP": "SGP",
"Japan": "SGP",
"Singapore": "SGP"
}
使用嵌套迭代的字典理解:
>>> 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", ...
因此:
{i: k ...}
->{"US": "USA", ...}