Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8742517
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T11:31:03+00:00 2026-06-13T11:31:03+00:00

Given a string s , I want to know how many times each character

  • 0

Given a string s, I want to know how many times each character at the string occurs. Here is the code:

def main() :
  while True :
    try :
      line=raw_input('Enter a string: ')
    except EOFError :
      break;
    mp={};

    for i in range(len(line)) :
      if line[i] in mp :
        mp[line[i]] += 1;
      else :
        mp[line[i]] = 1;

    for i in range(len(line)) :
      print line[i],': ',mp[line[i]];

if __name__ == '__main__' :
  main();

When I run this code and I enter abbba, I get:

a : 2
b : 3
b : 3
b : 3
a : 2

I would like to get only:

a : 2
b : 3

I understand why this is happening, but as I’m new to python, I don’t know any other ways to iterate over the elements of a map. Could anyone tell me how to do this? Thanks in advance.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-13T11:31:04+00:00Added an answer on June 13, 2026 at 11:31 am

    You could try a Counter (Python 2.7 and above; see below for a pre-2.7 option):

    >>> from collections import Counter
    >>> Counter('abbba')
    Counter({'b': 3, 'a': 2})
    

    You can then access the elements just like a dictionary:

    >>> counts = Counter('abbba')
    >>> counts['a']
    2
    >>> counts['b']
    3
    

    And to iterate, you can use @BurhanKhalid’s suggestion (the Counter behaves as a dictionary, where you can iterate over the key/value pairs):

    >>> for k, v in Counter('abbba').iteritems():
    ...   print k, v
    ...
    a 2
    b 3
    

    If you’re using a pre-2.7 version of Python, you can use a defaultdict to simplify your code a bit (process is still the same – only difference is that now you don’t have to check for the key first – it will ‘default’ to 0 if a matching key isn’t found). Counter has other features built into it, but if you simply want counts (and don’t care about most_common, or being able to subtract, for instance), this should be fine and can be treated just as any other dictionary:

    >>> from collections import defaultdict
    >>> counts = defaultdict(int)
    >>> for c in 'abbba':
    ...   counts[c] += 1
    ...
    >>> counts
    defaultdict(<type 'int'>, {'a': 2, 'b': 3})
    

    When you use iteritems() on a dictionary (or the Counter/defaultdict here), a key and a value are returned for each iteration (in this case, the key being the letter and the value being the number of occurrences). One thing to note about using dictionaries is that they are inherently unordered, so you won’t necessarily get 'a', 'b', ... while iterating. One basic way to iterate through a dictionary in a sorted manner would be to iterate through a sorted list of the keys (here alphabetical, but sorted can be manipulated to handle a variety of options), and return the dictionary value for that key (there are other ways, but this will hopefully be somewhat informative):

    >>> mapping = {'some': 2, 'example': 3, 'words': 5}
    >>> mapping
    {'some': 2, 'example': 3, 'words': 5}
    >>> for key in sorted(mapping.keys()):
    ...   print key, mapping[key]
    ...
    example 3
    some 2
    words 5
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I need to calculate how many times every character occurs in the given string.
Given the following code: int i; ... ostingstream os; os<<i; string s=os.str(); I want
Given this string random_string= '4' i want to determine if its an integer, a
Given a string, I want to retrieve a string that is in between the
Given a string such as 2*(i+j) <= 100 I want to generate the corresponding
Given a string such as: a:2:{i:0;s:1:1;i:1;s:1:2;} I want to find every integer within quotes
Given a string string result = "01234" I want to get the separate integers
I want to use this for an object factory: Given a string, create a
Let's say I'm given a string, and I want to define a function with
Given a datetime string like this: 2012-06-19 03:44:39 I want to use it to

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.