【问题标题】:Python dicts, take a dictionary and return a dict where the keys are one of the values from the former dict and the values are the keysPython dicts,取一个字典并返回一个字典,其中键是前一个字典的值之一,值是键
【发布时间】:2021-10-09 21:30:26
【问题描述】:

我正在尝试编写一个接受字典的函数:

sites = {
   42: ("Christchurch", "Canterbury"),
 8472: ("Timaru", "Canterbury"),
   11: ("Westport", "Westland")
}

一个返回:

{'Canterbury': [42, 8472], 'Westland': [11]}

我目前有:

sites_dict = {}
for site_id, site in sites_info.items():
    city, region = site
    sites_dict[region] = [site_id]
    if region in sites_dict:
        site_id = [site_id]
       

每次循环时只返回替换值。 谢谢。

【问题讨论】:

  • 韦斯特波特和蒂马鲁发生了什么事?
  • @DaniMesejo,看起来值是元组(城市,地区),他们只是希望地区作为键。
  • 我在新的字典中不需要它们中的任何一个。只有 Christchurch,Timaru 共享一个元组的相同值,他们所在的地区,所以我要收集他们的密钥。
  • 目前我的函数返回 {'Canterbury': [8472], 'Westland': [11]}

标签: python python-3.x dictionary


【解决方案1】:

使用collections.defaultdict:

from collections import defaultdict

sites = {
   42: ("Christchurch", "Canterbury"),
 8472: ("Timaru", "Canterbury"),
   11: ("Westport", "Westland")
}

result = defaultdict(list)
for key, (_, site) in sites.items():
    result[site].append(key)

print(result)

输出

defaultdict(<class 'list'>, {'Canterbury': [42, 8472], 'Westland': [11]})

或者使用简单的字典:

result = {}
for key, (_, site) in sites.items():
    if site not in result:
        result[site] = []
    result[site].append(key)

print(result)

输出

{'Canterbury': [42, 8472], 'Westland': [11]}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-14
    • 1970-01-01
    相关资源
    最近更新 更多