如何使用Python中的用户ID迭代自定义Json数据

如何使用Python中的用户ID迭代自定义Json数据,python,json,python-3.x,Python,Json,Python 3.x,我想用值x和y构建一个定制的Json。我想通过它的用户ID来迭代它 (假设,x和y是一些计算变量) 例如: 输入数据 [ { "userID": "1acv", "debit": 2000, "Balance": 15000, "date": "2018-03-28" }, { "userID": "1acv", "debit": 1000, "Balance": 14000, "date": "2018-03-29"

我想用值xy构建一个定制的Json。我想通过它的用户ID来迭代它 (假设,xy是一些计算变量)

例如:
输入数据

[
  {
    "userID": "1acv",
    "debit": 2000,
    "Balance": 15000,
    "date": "2018-03-28"
  },
  {
    "userID": "1acv",
    "debit": 1000,
    "Balance": 14000,
    "date": "2018-03-29"
  },
  {
    "userID": "1acv",
    "debit": 5000,
    "Balance": 9000,
    "date": "2018-03-30"
  },
  {
    "userID": "2acv",
    "debit": 500,
    "Balance": 5000,
    "date": "2018-02-03"
  },
  {
    "userID": "2acv",
    "debit": 1500,
    "Balance": 3500,
    "date": "2018-02-03"
  },
  {
    "userID": "2acv",
    "debit": 500,
    "Balance": 3000,
    "date": "2018-02-03"
  }
]
代码

with open('/path/data.json', 'r') as f:
    reader = json.load(f)
#Calculation is done to find the values x and y
js = {
     "UserID": userID,
     "Total Debit": x,
     "Avg Debit": y
     }
with open('/path/test.json', 'w') as outfile:
     json.dump(js, outfile)
预期的Json输出:

我想计算每个用户ID的借项和平均借项

[
{"userID": "1acv", "Total Debits": 8000,"Avg Debit": 2666.6666},
{"userID": "2acv", "Total Debits": 2500,"Avg Debit": 833.3333}
]

PS:我对Json或Csv输出都没问题

这里有一种使用集合的方法。defaultdict():


但在处理非常大的数据集时,这可能不是最有效的方法。为了避免执行两次
sum(debitis)
,您可能希望为
defaultdict
使用另一个构造函数,如
int
,而不是列出并保留
debitis的总和和每个用户id的项目数。

实际上
js
中有60多个变量(不仅仅是
debit
)。那么,我是否需要在所有变量中附加
I['value']
?有没有其他方法可以解决这个问题呢?
i['value']
是什么?
d[i['userID']]。追加(i['debit'])
而不是
debit
我写了
value
来解释60多个变量,这没有任何区别,您可以使用这种方法,但是如果您需要更快的解决方案,或者您对当前的性能不满意,您可以按照我说的做。
In [21]: from collections import defaultdict

In [22]: d = defaultdict(list)

In [23]: for i in js:
    ...:     d[i['userID']].append(i['debit'])
    ...:     
    ...: 

In [24]: 
    ...: [{"userID": "1acv", "Total Debits": sum(debits),"Avg Debit": sum(debits)/len(debits)} for id_, debits in d.items()]
Out[24]: 
[{'userID': '1acv', 'Total Debits': 8000, 'Avg Debit': 2666.6666666666665},
 {'userID': '1acv', 'Total Debits': 2500, 'Avg Debit': 833.3333333333334}]