使用默认dict进行排序

时间:2014-04-02 20:18:47

标签: python json string ipython

我有一个Python代码,见下文,其中包含结构中的JSON文件:

{
    "name":"Winking Entertainment",
    "imports":"Translink Capital"
  },
  {
    "name":"Wochacha",
    "imports":"Sequoia Capital"
  },
  {
    "name":"Wuhan Kindstar Diagnostics",
    "imports":"Baird Venture Partners"
  },

聚合在“imports”中重复值,并将匹配的字符串转换为该条目的单个数组。 (见下面的摘录)

   import json

from collections import defaultdict

def map_names_to_imports(raw_data):
  name_to_imports = defaultdict(list)
  for row in raw_data:
     name_to_imports[row['imports']].append(row['name'])
  return name_to_imports

def reformat(name_to_imports):
  output = []
  for name, imports in name_to_imports.items():
    new_dict = {
      'name': name,
      'imports': list(set(imports))
    }
    output.append(new_dict)
  return output

def run(raw_data):
  name_to_imports = map_names_to_imports(raw_data)
  output = reformat(name_to_imports)
  with open('clean-data2.json','wb') as f:
    f.write(json.dumps(output))

if __name__ == '__main__':
  raw_data = json.load(open('bricinvestors.json'))
  run(raw_data)

我遇到的问题是我的Json文件没有以正确的方式出现。

出于某种原因,名称和进口正在逆转。所以我的输出看起来像:

  {"imports": ["SinoHub"], "name": "Iroquois Capital"}, {"imports": ["Qunar.com", "Lashou.com"], "name": "Tenaya Capital"}

事实上,我想保留{“name”:“string”,“imports”:“string”}格式 - 而不是相反。

我该怎么办?

感谢。

3 个答案:

答案 0 :(得分:1)

如果您使用的是Python 2.7+,则可以使用collections.OrderedDict 作为json.loads()的输入,而不是标准的Python dict。标准库dict类不保证密钥的排序。

答案 1 :(得分:0)

dano's answer上构建,您可以使用OrderedDict.setdefault方法而不是使用defaultdict:

import json
import collections
OrderedDict = collections.OrderedDict

def map_names_to_imports(raw_data):
    name_to_imports = OrderedDict()
    for row in raw_data:
        name_to_imports.setdefault(row['imports'], []).append(row['name'])
    return name_to_imports


def reformat(name_to_imports):
    output = []
    for name, imports in name_to_imports.items():
        new_dict = OrderedDict([('name', name),
                                ('imports', list(set(imports)))])
        output.append(new_dict)
    return output


def run(raw_data):
    name_to_imports = map_names_to_imports(raw_data)
    output = reformat(name_to_imports)
    with open('clean-data2.json', 'wb') as f:
        f.write(json.dumps(output))

if __name__ == '__main__':
    raw_data = json.load(open('bricinvestors.json'),
                         object_pairs_hook=OrderedDict)
    run(raw_data)

答案 2 :(得分:0)

最终版本,主要基于@ unutbu的答案。

import json
import collections
OrderedDict = collections.OrderedDict

def map_names_to_imports(raw_data):
    name_to_imports = OrderedDict()
    for row in raw_data:
        name_to_imports.setdefault(row['imports'], []).append(row['name'])
    return name_to_imports

def reformat(name_to_imports):
    the_output = []
    for name, imports in name_to_imports.items():
        new_dict = OrderedDict([('name', name),
                                ('imports', list(set(imports)))])
        the_output.append(new_dict)
    return the_output

def run(raw_data):
    name_to_imports = map_names_to_imports(raw_data)
    the_output = reformat(name_to_imports)
    with open('data/clean-data2.json',  'w+', encoding='utf8') as f:
        f.write(json.dumps(the_output))

if __name__ == '__main__':
  raw_data = json.load(open('data/bricsinvestorsfirst.json'), object_pairs_hook=OrderedDict)
  run(raw_data)