[英]Python 3.x - Mapping dictionary with multiple tuples as keys
I have a dictionary containing multiple tuple as keys:我有一个包含多个元组作为键的字典:
dictionary = {('Paris', 'Monaco', 'Marseille'): 'France',
('Milan', 'Juventus', 'Roma'): 'Italy',
('Manchester', 'Liverpool', 'London'): 'England'}
How to mapping list with lot of city names to the dictionary above:如何将包含大量城市名称的列表映射到上面的字典:
lst = ['Paris','Paris','Monaco','Milan','London',...]
I have tried this:我试过这个:
countries = []
for k,v in dictionary.items():
for each in lst:
if each in k:
countries.append(v)
Results: It wasnt assign the city dictionary one-by-one instead listing all keys multiple times结果:它不是一一分配城市字典而是多次列出所有键
Desired output:期望的输出:
lst countries
Paris France
Paris France
Monaco France
Milan Italy
London England
... ...
Any ideas?有任何想法吗?
I suggest you flatten the dictionary keys.我建议你展平字典键。 Duplicating values across keys isn't an issue:
跨键复制值不是问题:
dictionary = {k: v for tup, v in dictionary.items() for k in tup}
Then use the new dictionary to easily build your list:然后使用新词典轻松构建您的列表:
countries = [dictionary[city] for city in lst]
You can match city and country side by side like so:您可以像这样并排匹配城市和国家:
for city, country in zip(lst, countries):
print(city, country)
Or without building the new countries
list, you can use the new dictionary directly:或者不构建新的
countries
列表,你可以直接使用新的字典:
for city in lst:
print(city, dictionary[city])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.