python嵌套字典中的选择性展平和查找键

时间:2015-04-08 09:21:26

标签: python dictionary

我有这种格式的数据存在于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"}
   }]

这是我的代码

 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)

我想删除嵌套字典(LOCATION1,此处格式化后 - 之前是LOCATION)但保留ADDLINE2,3,PIN同样如此。我想要一个扁平的字典。我能做些什么来即兴发挥它?

我需要这种形式的密钥 的 [姓名,电子邮件,地址,位置{addline2,addline3,销}] 即使添加了额外的嵌套值,它也应该以这种形式动态显示

1 个答案:

答案 0 :(得分:0)

 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())

由于最后一行,上面的所有内容都无用,重置数据。 在所有其他事项

之前,将ADDLINE2,3,PIN添加到上面的循环中
row['ADDLINE2'] = row['LOCATION']['ADDLINE2']
row['ADDLINE3'] = row['LOCATION']['ADDLINE3']
row['PIN '] = row['LOCATION']['PIN ']