Python JSON - 根据“类别”获取多少结果

时间:2014-03-08 14:22:27

标签: python json csv

 [       
 {
    "account" : "",
    "address" : "D8xWhR8LqSdSLTxRWwouQ3EiSnvcjLmdo6",
    "category" : "send",
    "amount" : -1000.00000000,
    "fee" : -0.00000001,
    "confirmations" : 716,
    "blockhash" : "4569322b4c8c98fba3ef4c7bda91b53b4ee82d268eae2ff7658bc0d3753c00ff",
    "blockindex" : 2,
    "blocktime" : 1394242415,
    "txid" : "45b629a779e6e0bf6d160c37833a27f1f2cc1bfa34632d166cccae83e69eb6fe",
    "time" : 1394242259,
    "timereceived" : 1394242259
    },
    {
    "account" : "",
    "address" : "DCPFe1fs7qScDFvoTexYqo95LmnJJkjmu7",
    "category" : "receive",
    "amount" : 0.13370000,
    "confirmations" : 717,
    "blockhash" : "e9024e177b42ca23fed741fb90c39836de5f9c722a93157e50df2e3f2c318d77",
    "blockindex" : 26,
    "blocktime" : 1394242412,
    "txid" : "ce41b4c35b09ae582436b8138d62375840c32bd9ea0360457bd9f589012d2da3",
    "time" : 1394242315,
    "timereceived" : 1394242315
    },
    {
    "account" : "",
    "address" : "DCPFe1fs7qScDFvoTexYqo95LmnJJkjmu7",
    "category" : "receive",
    "amount" : 0.00100000,
    "confirmations" : 692,
    "blockhash" : "17eb2ef40b8bcb2ceb3d7f07d6545f03fc9bf41c8d28f759becd84a31e65e123",
    "blockindex" : 14,
    "blocktime" : 1394243788,
    "txid" : "2b099fd0ce6239c5c3c69e2ba70669c3069858908e42b8ca970bf213e555d715",
    "time" : 1394243669,
    "timereceived" : 1394243669
    },
    {
    "account" : "",
    "address" : "DCPFe1fs7qScDFvoTexYqo95LmnJJkjmu7",
    "category" : "send",
    "amount" : -0.00100000,
    "fee" : -2.00000000,
    "confirmations" : 692,
    "blockhash" : "17eb2ef40b8bcb2ceb3d7f07d6545f03fc9bf41c8d28f759becd84a31e65e123",
    "blockindex" : 14,
    "blocktime" : 1394243788,
    "txid" : "2b099fd0ce6239c5c3c69e2ba70669c3069858908e42b8ca970bf213e555d715",
    "time" : 1394243669,
    "timereceived" : 1394243669
    }
    ]

那^^是我的数据。

我怎样才能看到有多少"条目"有"类别" =="收到"

我想这样做,所以我可以正确地遍历它们(使用while循环和interment)

有没有更好的方法来做我想要的事情?

我知道用csv可以做到

for row in reader

1 个答案:

答案 0 :(得分:5)

您可以使用这样的生成器表达式,并且可以将表达式的结果提供给sum函数,以获得categoryreceive <的条目总数/ p>

sum(item["category"] == "receive" for item in my_list_of_dicts)

这几乎相当于

result = 0
for item in my_list_of_dicts:
    if item["category"] == "receive":
        result += 1

编辑:如果您正在阅读该文件,那么您应该像这样加载json数据

import json
my_list_of_dicts = json.load(open("Input.txt"))
相关问题