Reputation: 3081
I want to map a subset of a dictionary to attributes of a class but with different names. 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. I also want these attributes to be None if the corresponding keys are not present in the dict. Is there an easy way and direct way to do this without explicitly checking for each specific key?
Upvotes: 1
Views: 1066
Reputation: 4045
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)
Upvotes: 2