从 key/values 字典中丰富我的列表

Enrich my list from a key/values dictionnary

class Person:
    def __init__(self, name, city, country=""):
        self.name = name
        self.city = city
        self.country = country
    
    def __str__(self):
        return 'Person[' + self.name + "," + self.city + "," + self.country + ']'

cities_to_countries = {
      'Beijing': 'China',
      'London': 'United Kingdom',
      'San Francisco': 'United States',
      'Singapore': 'Singapore',
      'Sydney': 'Australia'
  }

persons = [
      Person('Henry', 'Singapore'),
      Person('Jane', 'San Francisco'),
      Person('Lee', 'Beijing'),
      Person('John', 'Sydney'),
      Person('Alfred', 'London')
  ]

嘿,我想将国家/地区添加到我的 persons.country。例如,我希望 Jane 通过匹配我的字典 key/values 和我的列表

将旧金山作为一个城市,将美国作为一个国家

遍历您的人员列表并使用城市作为字典中的关键字设置人员国家:

for peep in persons:
    peep.country = cities_to_countries[peep.city]