简体   繁体   中英

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 having a list as the value of my dictionary,increasing the first element(index 0) by 1 each time an existing character is found and appending the same list of the dict value by the Index of the character in the word eg Word="Programming is nature" Dict={'a':[2,5,16],'i':[2,8,12]...etc}

So the first index of each dict value increases by the occurrence of a character(ie +1 if the character is found) but the other values in the list are appended(holding the location a char is found in the word). I have this for the counting alone but not for the indexing

def count(word):
    v=0;b={}
    b.clear()
    while word[v] in word:
        if word[v] in b.keys():
            b[word[v]]+=1;v+=1
        else:
            b[word[v]]=1;v+=1
        if v==(len(word)):
            break
    print("\n",b)


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

Use a collections.defaultdict instead:

import collections

def count(word):
    c = collections.defaultdict(list)
    for index, letter in enumerate(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]})

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]}

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

def count(word):
    counts = defaultdict(int)
    appearances = defaultdict(list)
    for pos, val in enumerate(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).

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

Using defaultdict a little differently:

from collections import defaultdict
example = 'Programming is nature'
D=defaultdict(lambda: [0])
for i,c in enumerate(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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM