[英]selective flattening in python nested dictionary and finding keys
i have the data in this format present in json file 我在json文件中使用这种格式的数据
[
{
"FIRST NAME": "Nasim",
"EMAIL": "ac@iaculisnec.net",
"ADDLINE1": "855-8805 Nunc. Avenue",
"CITY": "Masterton",
"LOCATION":{"ADDLINE2":"855-8805",
"ADDLINE3":"Avenue",
"PIN":"100"}
},
{
"FIRST NAME": "Xanthus",
"EMAIL": "adipiscing.elit@tinciduntcongue.edu",
"ADDLINE1": "357-4583 Curae; St.",
"CITY": "Basildon",
"LOCATION":{"ADDLINE2":"357-4583",
"ADDLINE3":"Curae; St.",
"PIN":"101"}
},
{
"FIRST NAME": "Hedley",
"EMAIL": "Quisque.libero.lacus@arcu.ca",
"ADDLINE1": "315-623 Nibh. Road",
"CITY": "Abingdon",
"LOCATION":{"ADDLINE2":"315-623",
"ADDLINE3":"Nibh. Road",
"PIN":"102"}
}]
this is my code 这是我的代码
data=json.loads(file('grade.json').read())
for row in data:
row['ADDRESS']= row['ADDLINE1']+','+ row['CITY']
del row['CITY'], row['ADDLINE1']
row['LOCATION1']=row['LOCATION']['ADDLINE2']+','+row['LOCATION'] ['ADDLINE3']+','+row['LOCATION']['PIN']
del row['LOCATION']
data =json.loads(file('grade.json').read())
out = {}
for sub in data.values():
for key, value in sub.items():
if key in out:
del out[key]
else:
out[key] = value
print(out)
file('files','w').write(json.dumps(data))
out_path= "outfile9.csv"
fieldnames = list(set(k for d in data for k in d))
with open(out_path, 'wb') as out_file:
writer = csv.DictWriter(out_file, fieldnames=fieldnames, dialect='excel')
writer.writeheader()
writer.writerows(data)
i want to remove d nested dictionary(LOCATION1, here after formatting-previously was LOCATION) but retain ADDLINE2,3,PIN as the same. 我想删除d嵌套字典(LOCATION1,这里在格式化之前为LOCATION),但保留ADDLINE2,3,PIN不变。 i want a flattened dictionary.
我想要一个扁平的字典。 what can i do to improvise it?
我该怎么做才能即兴创作?
i require keys in this form [firstname,email,address,location{addline2,addline3,pin}] even if extra nested values are added it should dynamically appear in this form 我需要这种形式的密钥[firstname,email,address,location {addline2,addline3,pin}],即使添加了额外的嵌套值,它也应该以这种形式动态显示
data=json.loads(file('grade.json').read())
for row in data:
row['ADDRESS']= row['ADDLINE1']+','+ row['CITY']
del row['CITY'], row['ADDLINE1']
row['LOCATION1']=row['LOCATION']['ADDLINE2']+','+row['LOCATION'] ['ADDLINE3']+','+row['LOCATION']['PIN']
del row['LOCATION']
data =json.loads(file('grade.json').read())
the above is all useless because of the last line, resets data. 由于最后一行,以上全部无效,将重置数据。 to flatten ADDLINE2,3,PIN , add in the above loop, before everything else
展平ADDLINE2,3,PIN,在上面的循环中添加其他内容
row['ADDLINE2'] = row['LOCATION']['ADDLINE2']
row['ADDLINE3'] = row['LOCATION']['ADDLINE3']
row['PIN '] = row['LOCATION']['PIN ']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.