Search code examples
pythonpython-3.xcounter

Counting occurence of each key


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)

Solution

  • 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)