Counting occurence of each key

Question:

I have the following users as

users = [
  { username: "user1", state: "USA" },
  { username: "user2", state: "Canada" },
  { username: "user3", state: "China" },
  { username: "user4", state: "China" },
  { username: "user4", state: "USA" },
];

I want to count the number of occurence of each state and print it along with its value.
My output should be something like

USA, 2
Canada,1
China,2

I have made use of counter in python but am facing issues.

users = [
  { username: "user1", state: "USA" },
  { username: "user2", state: "Canada" },
  { username: "user3", state: "China" },
  { username: "user4", state: "China" },
  { username: "user4", state: "USA" },
];
from collections import Counter

counts = Counter(c for c in 'users' if c in 'USA, Canada, China')
for k,v in counts.iteritems():
    print(k,v)
Asked By: abcd

||

Answers:

The syntax { username: "user1", state: "USA" }, works only in javascript, in python you need quotes around keys too : {"username": "user1", "state": "USA" },


You also iterate on 'users', that is a string, you need to use your variable users, then take the state part with c['part']

from collections import Counter

users = [
    {"username": "user1", "state": "USA"}, {"username": "user2", "state": "Canada"},
    {"username": "user3", "state": "China"}, {"username": "user4", "state": "China"},
    {"username": "user4", "state": "USA"},
]
counts = Counter(c['state'] for c in users)

for k, v in counts.items():
    print(k, v)

# iterate on descending count order
for k, v in counts.most_common():
    print(k, v)
Answered By: azro

# without using in built module. Find occurence of each value
s = [1, 4, 6, 3, 8, 3, 2, 1, 1]
d = {}
for i in s:
    if i not in d:
        d[i] = 1
    else:
        d[i] += 1
print(d)

without using inbuilt module in Python. Find occurrence of each value given in List.

s = [1, 4, 6, 3, 8, 3, 2, 1, 1]
d = {}

for i in s:
if i not in d:
d[i] = 1
else:
d[i] += 1
print(d)
Ans-
{1: 3, 4: 1, 6: 1, 3: 2, 8: 1, 2: 1}

[enter image description here][1]#

Answered By: jayesh verma

Another alternate approach can be wehre you can avoid using the Counter module and define your own counter dictionary.

counter = {}
for user in users:
    if counter.get(user['state']) == None:
        counter[user['state']] = 1
    else:
        counter[user['state']] += 1

print(counter)

{'USA': 2, 'Canada': 1, 'China': 2}
Answered By: Sumit Trehan
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.