简体   繁体   English

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

[英]Mapping a Python dictionary to new attributes in an object

I want to map a subset of a dictionary to attributes of a class but with different names.我想将字典的子集 map 转换为 class 但名称不同的属性。 For eg:例如:

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

I want to map the above dictionary to an Object with attributes "Name", "Forecast" and "AreaCode" with values of "Minneapolis", "Sunny with chance of rain" and 651 respectively while ignoring other keys.我想将上述字典 map 转换为 Object 属性“名称”、“预测”和“区域代码”,其值分别为“明尼阿波利斯”、“有雨的晴天”和 651,同时忽略其他键。 I also want these attributes to be None if the corresponding keys are not present in the dict.如果字典中不存在相应的键,我还希望这些属性为 None 。 Is there an easy way and direct way to do this without explicitly checking for each specific key?有没有一种简单的方法和直接的方法可以在不明确检查每个特定键的情况下做到这一点?

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM