Skip to content Skip to sidebar Skip to footer

Appending Values Of Dict List

I'm making a sample program that counts how many occurrences a character is in a given word. Say 'Good',g occurred once,o occurred 2 times etc. Now I wanna try to further this by h

Solution 1:

Use a collections.defaultdict instead:

import collections

defcount(word):
    c = collections.defaultdict(list)
    for index, letter inenumerate(word):
        c[letter] += [index]
    return c

print count('programming is nature')

Output:

defaultdict(<type'list'>, {'a': [5, 16], ' ': [11, 14], 'e': [20], 'g': [3, 10], 'i': [8, 12], 'm': [6, 7], 'o': [2], 'n': [9, 15], 'p': [0], 's': [13], 'r': [1, 4, 19], 'u': [18], 't': [17]})

Solution 2:

If you are on Python 2.7+, use Counter:

>>> from collections import Counter
>>> Counter('abchfdhbah')
Counter({'h': 3, 'a': 2, 'b': 2, 'c': 1, 'd': 1, 'f': 1})
>>> the_count = Counter('abchfdhbah')
>>> the_count['h']
3

Solution 3:

Here was my solution:

def count(word):
    b={}
    for i,letter in enumerate(word):
        if letter not in b:
            b[letter]=[0]
        b[letter][0]+=1
        b[letter].append(i)
return b

print(count("Programming is nature"))

word="Programming is nature" print(count(word))

Works exactly the way you want it to. :)

Output:

{'a': [2, 5, 16], ' ': [2, 11, 14], 'e': [1, 20], 'g': [2, 3, 10], 'i': [2, 8, 12], 'm': [2, 6, 7], 'o': [1, 2], 'n': [2, 9, 15], 'P': [1, 0], 's': [1, 13], 'r': [3, 1, 4, 19], 'u': [1, 18], 't': [1, 17]}

Solution 4:

Ok, so some notes first.

You should be using raw_input instead of input; input evaluates what you enter as Python code, raw_input gets input from stdin (ignore this if you're using Python 3). If you have a specific, default value your dict values can take, collections.defaultdict is very useful.

from collections import defaultdict

defcount(word):
    counts = defaultdict(int)
    appearances = defaultdict(list)
    for pos, val inenumerate(word)
        counts[val] += 1
        appearances[c].append(pos)

    print'counts:', counts
    print'appearances:', appearances

word = input("Enter word: ")
count(word)

defaultdict takes a callable as its argument, so if you do:

x = defaultdict(int)
x['b'] += 1

since 'b' is not a key in x, it initializes it to the value of int() (which is zero).

Solution 5:

Using defaultdict a little differently:

from collections import defaultdict
example = 'Programming is nature'
D=defaultdict(lambda: [0])
for i,c inenumerate(example):
    D[c][0] += 1
    D[c].append(i)
for k,v in D.items():
    print(k,v)

Output matching your example:

a[2, 5, 16][2, 11, 14]
e [1, 20]
g [2, 3, 10]i[2, 8, 12]
m [2, 6, 7]
o [1, 2]
n [2, 9, 15]P[1, 0]
s [1, 13]
r [3, 1, 4, 19]
u [1, 18]
t [1, 17]

Post a Comment for "Appending Values Of Dict List"