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.
You could try a Counter (Python 2.7 and above; see below for a pre-2.7 option):
You can then access the elements just like a dictionary:
And to iterate, you can use @BurhanKhalid’s suggestion (the
Counterbehaves as a dictionary, where you can iterate over the key/value pairs):If you’re using a pre-2.7 version of Python, you can use a
defaultdictto 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).Counterhas other features built into it, but if you simply want counts (and don’t care aboutmost_common, or being able tosubtract, for instance), this should be fine and can be treated just as any other dictionary:When you use
iteritems()on a dictionary (or theCounter/defaultdicthere), 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, butsortedcan 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):