Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over the elements of a map in python

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.

like image 205
Rontogiannis Aristofanis Avatar asked Oct 27 '12 08:10

Rontogiannis Aristofanis


4 Answers

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
like image 192
RocketDonkey Avatar answered Sep 19 '22 07:09

RocketDonkey


Iterating over a mapping yields keys.

>>> d = {'foo': 42, 'bar': 'quux'}
>>> for k in d:
...   print k, d[k]
... 
foo 42
bar quux
like image 20
Ignacio Vazquez-Abrams Avatar answered Sep 18 '22 07:09

Ignacio Vazquez-Abrams


You need to look up the help for dict(). It's all there -- 'for k in mp' iterates over keys, 'for v in mp.values()' iterates over values, 'for k,v in mp.items()' iterates over key, value pairs.

Also, you don't need those semicolons. While they are legal in Python, nobody uses them, there's pretty much no reason to.

like image 23
kampu Avatar answered Sep 18 '22 07:09

kampu


Python 2.5 and above

  dDIct = collections.defaultdict(int)
  [(d[i]+=1) for i in line]
  print dDict
like image 40
Michael Avatar answered Sep 20 '22 07:09

Michael