【问题标题】:Python 3.x - Mapping dictionary with multiple tuples as keysPython 3.x - 以多个元组作为键的映射字典
【发布时间】:2018-03-27 16:27:55
【问题描述】:

我有一个包含多个元组作为键的字典:

dictionary = {('Paris', 'Monaco', 'Marseille'): 'France',
               ('Milan', 'Juventus', 'Roma'): 'Italy',
               ('Manchester', 'Liverpool', 'London'): 'England'}

如何将包含大量城市名称的列表映射到上面的字典:

lst = ['Paris','Paris','Monaco','Milan','London',...]

我试过这个:

countries = []
for k,v in dictionary.items():
    for each in lst:
        if each in k:
            countries.append(v)

结果:它不是一一分配城市字典,而是多次列出所有键

期望的输出:

lst        countries
Paris       France
Paris       France
Monaco      France
Milan       Italy
London      England
...         ...

有什么想法吗?

【问题讨论】:

  • 为什么你的字典里有这种格式?为什么不让城市分开键和重复值?
  • 假设我的字典中有很多键和值,很难用重复值创建单独的键
  • 用单独的键制作一本新字典困难。如果您有很多键和值,那么就更重要了,您可以避免一直循环遍历所有键。

标签: python list dictionary mapping


【解决方案1】:

我建议你扁平化字典键。跨键重复值不是问题:

dictionary = {k: v for tup, v in dictionary.items() for k in tup}

然后使用新字典轻松构建您的列表:

countries = [dictionary[city] for city in lst]

你可以像这样并排匹配城市和国家:

for city, country in zip(lst, countries):
    print(city, country)

或者不构建新的countries列表,直接使用新字典即可:

for city in lst:
    print(city, dictionary[city])

【讨论】:

  • 它有效,我认为缺少的链接是我不知道如何展平字典键。谢谢。
猜你喜欢
  • 1970-01-01
  • 2017-06-28
  • 2018-12-31
  • 1970-01-01
  • 2019-05-09
  • 2014-10-06
  • 2018-07-22
  • 1970-01-01
  • 2015-10-29
相关资源
最近更新 更多