我多次调用API并最终将结果写入CSV。我有以下代码从dict
中提取数据:
city = data['property'][0]['address']['locality']
zip_code = data['property'][0]['address']['postal1']
county = data['property'][0]['area']['countrysecsubd']
condition = data['property'][0]['building']['construction']['condition']
roof = data['property'][0]['building']['construction']['roofcover']
bathrooms = data['property'][0]['building']['rooms']['bathstotal']
bedrooms = data['property'][0]['building']['rooms']['beds']
total_number_of_rooms = data['property'][0]['building']['rooms']['roomsTotal']
square_footage = data['property'][0]['building']['size']['bldgsize']
year_built = data['property'][0]['summary']['yearbuilt']
number_of_stories = data['property'][0]['building']['summary']['levels']
lot_size1 = data['property'][0]['lot']['lotsize1']
lot_size2 = data['property'][0]['lot']['lotsize2']
latitude = data['property'][0]['location']['latitude']
longitude = data['property'][0]['location']['longitude']
dict
的结构是here在Pastebin上,因为它占用了很多空间。你知道吗
如何用更少的代码获得相同的结果?你知道吗
你这样做的方式是“Python”。但是,还有其他替代方法,其中一种方法是像使用对象(或子对象)属性一样使用关键点。不管它是不是有点像Python,都在旁观者的眼里。一旦脚手架就位,它肯定需要更少的打字,我觉得它也更可读。你知道吗
实现这种功能的一种方法是创建一个
dict
子类,它是自己的__dict__
。一旦定义了类,那么它的最外层和所有子字典都必须转换成AttrDict
实例。你知道吗下面的代码显示了我的意思:
编写一个助手函数,使您可以编写更少的样板文件:
呼叫:
等等
创建自己的dictionary类怎么样
那么,你可以这样称呼它
请注意,这是未经测试,只是一个想法,供您尝试。你知道吗
相关问题 更多 >
编程相关推荐