我有一个包含多个元组作为键的字典:
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
... ...
有什么想法吗?
答案 0 :(得分: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])