假设我有4个字典
x = {'id': 1, 'addressed_to': 2, 'status': 'open'}
y = {'id': 2, 'addressed_to': 2, 'status': 'open'}
z = {'id': 3, 'addressed_to': 2, 'status': 'closed'}
z = {'id': 4, 'addressed_to': 3, 'status': 'open'}
我对这种感兴趣
result = [{'addressed_to': 2, 'open': 2, 'closed':1},{'addressed_to':3 , 'open': 1, 'closed':0} ]
如何在python3中存档?
一个可能的答案是将字典移动到一个列表中,并对它们进行迭代以获得所需的答案。下面的示例代码。结果字典的关键字是addressed_to 的值
data_list = {"statsdata": [
{'id': 1, 'addressed_to': 2, 'status': 'open'},
{'id': 2, 'addressed_to': 2, 'status': 'open'},
{'id': 3, 'addressed_to': 2, 'status': 'closed'},
{'id': 4, 'addressed_to': 3, 'status': 'open'}
] }
p_result = {}
def checkItem(item):
if item["status"] == "open":
p_result[item["addressed_to"]]["open"] += 1
if item["status"] == "closed":
p_result[item["addressed_to"]]["closed"] += 1
for item in data_list["statsdata"]:
if item["addressed_to"] not in p_result:
p_result[item["addressed_to"]] = {'open':0, 'closed': 0}
checkItem(item)
else:
checkItem(item)
print(p_result)
结果将显示为
{2: {'open': 2, 'closed': 1}, 3: {'open': 1, 'closed': 0}}