json文件的问题(Python)

时间:2016-02-10 08:37:29

标签: python json

我的json文件有问题:Zips.json

我没有找到计算每个州邮政编码数量的方法。我尝试了很多这样的方法:

file=open("C:\Users\Alex\Downloads/zips.json","r")
lines=json.loads(file.readline())
number=0
states=lines["state"]
for line in file:
    lines=json.loads(line)
    if lines ["state"]==states:
        number=number+1
    else:
        print u"states:",states, u"Number of codes: ",number
        states=lines["state"]

1 个答案:

答案 0 :(得分:2)

最简单的方法是使用collections.Counter

import json
from collections import Counter
from operator import itemgetter

counter = None
state_getter = itemgetter('state')

with open('zips.json') as fh:
    zips_data = (json.loads(line) for line in fh)
    states_names = map(itemgetter('state'), zips_data)
    counter = Counter(states_names)

print(counter)