python - Nested for-loops and dictionaries in finding value occurrence in string -


i've been tasked creating dictionary keys elements found in string , values count number of occurrences per value.

ex.

"abracadabra" → {'r': 2, 'd': 1, 'c': 1, 'b': 2, 'a': 5} 

i have for-loop logic behind here:

xs = "hshhsf" xsunique = "".join(set(xs))  occurrences = [] freq = []  counter = 0  in range(len(xsunique)):     x in range(len(xs)):         if xsunique[i] == xs[x]:             occurrences.append(xs[x])             counter += 1     freq.append(counter)     freq.append(xsunique[i]) counter = 0  

this want do, except lists instead of dictionaries. how can make counter becomes value, , xsunique[i] becomes key in new dictionary?

the easiest way use counter:

>>> collections import counter >>> counter("abracadabra") counter({'a': 5, 'r': 2, 'b': 2, 'c': 1, 'd': 1}) 

if can't use python library, can use dict.get default value of 0 make own counter:

s="abracadabra" count={} c in s:     count[c] = count.get(c, 0)+1  >>> count {'a': 5, 'r': 2, 'b': 2, 'c': 1, 'd': 1}     

or, can use dict.fromkeys() set values in counter 0 , use that:

>>> counter={}.fromkeys(s, 0) >>> counter {'a': 0, 'r': 0, 'b': 0, 'c': 0, 'd': 0} >>> c in s: ...    counter[c]+=1 ...  >>> counter {'a': 5, 'r': 2, 'b': 2, 'c': 1, 'd': 1} 

if want least pythonic, i.e., might in c, maybe do:

  1. create list possible ascii values set 0
  2. loop on string , count characters present
  3. print non 0 values

example:

ascii_counts=[0]*255 s="abracadabra"  c in s:     ascii_counts[ord(c)]+=1  i, e in enumerate(ascii_counts):     if e:         print chr(i), e  

prints:

a 5 b 2 c 1 d 1 r 2 

that not scale use unicode, however, since need more 1 million list entries...


Comments

Popular posts from this blog

c# - Better 64-bit byte array hash -

webrtc - Which ICE candidate am I using and why? -

php - Zend Framework / Skeleton-Application / Composer install issue -