将Python字典映射到对象中的新属性

将Python字典映射到对象中的新属性,python,dictionary,attributes,Python,Dictionary,Attributes,我想将字典的子集映射到具有不同名称的类的属性。例如: D = { "City" : { "Name": "Minneapolis", "Weather Forecast": "Sunny with chance of rain", "Temperature" : 55 } "State": "MN", "Area Code": 651,

我想将字典的子集映射到具有不同名称的类的属性。例如:

D = { "City" : {
                "Name": "Minneapolis", 
                "Weather Forecast": "Sunny with chance of rain",
                "Temperature" : 55
               }
      "State": "MN",
      "Area Code": 651,
      "Country": "US"
    }

我想将上面的字典映射到一个对象,该对象的属性“Name”、“Forecast”和“AreaCode”的值分别为“Minneapolis”、“Sunny with chance of rain”和651,而忽略其他键。如果dict中没有相应的键,我还希望这些属性为None。有没有一种简单直接的方法可以做到这一点,而无需显式检查每个特定键?

没有,没有内置的方法可以获取一些任意嵌套的dict并用它实例化自定义对象。你必须自己编写代码
from dataclasses import dataclass


@dataclass
class City:
    name: str
    forecast: str
    area_code: int

    @classmethod
    def from_dict(cls, data):
        name = data.get('City').get('Name')
        forecast = data.get('City').get('Weather Forecast')
        area_code = data.get('Area Code')
        return cls(name, forecast, area_code)


# regular use:
c1 = City('Greensboro', 'Sunny', 336)
print(c1)
City(name='Greensboro', forecast='Sunny', area_code=336)



D = { "City" : {
                "Name": "Minneapolis",
                "Weather Forecast": "Sunny with chance of rain",
                "Temperature" : 55
               },
      "State": "MN",
      "Area Code": 651,
      "Country": "US"
    }

# alternate constructor using a dictionary
c2 = City.from_dict(D)
print(c2)
City(name='Minneapolis', forecast='Sunny with chance of rain', area_code=651)