0

I'm very new to Python and I need to make the code that counts the number of times each number appears in a list associated with a specific key. The program should then print out those counts on separate line

I was able to print out the count, but I have trouble printing them on separate lines. Here is what I was able to do so far:

import json

#####

def read_json(filename):
    dt = {}

    fh = open(filename, "r")
    dt = json.load(fh)

    return dt

##### 

def num_counter(dt):

    numbers = dt["daily_stock_prices"]


    counter = {}

    for number in numbers:
        counter[number] = 0

    for number in numbers:
         counter[number] += 1

    print counter

#####

filename = raw_input('Please enter the file name: ')

#####

r = read_json(filename)
num_counter(r)

I have tried to work on printing the counter on separate lines as seen below, but I remain unsuccessful. Any advice? I'm also not sure where to include it in my code.

def print_per_line(number_counts):

    for number in number_counts.key():

            count = word_counts[word]       

            print word,count

Here is the list if needed:

{
    "ticker": "MSFT",
    "daily_stock_prices": [0,1,5,10,12,15,11,9,9,5,15,20]
}

The final output should be:

item: count
item: count
...
J. Doe
  • 1
  • 2

2 Answers2

1

Try this:

def num_counter(dt):
    numbers = dt["daily_stock_prices"]
    counter = {}
    for number in numbers:
        counter[number]= counter.get(number, 0) + 1
    return counter

def print_per_line(num_count):
    for k,v in counter.iteritems():
       print str(k) + ":  " + str(v)

# You call them like this
r = read_json(filename)
num_count = num_counter(r)
print_per_line(num_count)
chinmay
  • 672
  • 6
  • 15
0

Here is how to do it both with and without the collections module.

import collections
import json

# Here is the sample data
data = """{
    "ticker": "MSFT",
    "daily_stock_prices": [0,1,5,10,12,15,11,9,9,5,15,20]
}"""

# It's easiest to parses it with as JSON.
d = json.loads(data)

# You can use the collections module to count.
counts = collections.Counter(d['daily_stock_prices'])

# Or you can create a dictionary of the prices.
pricedict = {}
for price in d['daily_stock_prices']:
    if pricedict.has_key(price):
        pricedict[price] += 1
    else:
        pricedict[price] = 1

# Print output - you could substitute counts for pricedict. 
for k,v in pricedict.iteritems():
    print("{} - {}".format(k, v))

OUTPUT

0 - 1
1 - 1
5 - 2
9 - 2
10 - 1
11 - 1
12 - 1
15 - 2
20 - 1
>>>
Thane Plummer
  • 7,966
  • 3
  • 26
  • 30