python - Sub-dictionary erroneously repeated throughout dictionary? -
i'm trying store in dictionary number of times given letter occurs after given letter. example, dictionary['a']['d'] give me number of times 'd' follows 'a' in short_list.
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] short_list = ['ford','hello','orange','apple'] # dictionary keep track of how given letter occurs tally = {} in alphabet: tally[a] = 0 # dictionary keep track of how given letter occurs after given letter # e.g. how many times 'd' follow 'a' -- master_dict['a']['d'] master_dict = {} in alphabet: master_dict[a] = tally def precedingletter(letter,word): if word.index(letter) == 0: return else: return word[word.index(letter)-1] in alphabet: word in short_list: b in alphabet: if precedingletter(b,word) == a: master_dict[a][b] += 1 however, entries of letters (the keys) in master_dict same. can't think of way tally each letter's occurrence after letter. can offer insight here?
if sub-dicts supposed updated independently after creation, need shallow copy them. easiest/fastest way .copy():
for in alphabet: master_dict[a] = tally.copy() the other approach initialize dict lazily. easiest way defaultdict:
from collections import defaultdict masterdict = defaultdict(lambda: defaultdict(int)) # or collections import counter, defaultdict masterdict = defaultdict(counter) no need pre-create empty tallies or populate masterdict @ all, , avoids creating dicts when letter never occurs. if access masterdict[a] a doesn't yet exist, creates defaultdict(int) value automatically. when masterdict[a][b] accessed , doesn't exist, count initialized 0 automatically.
Comments
Post a Comment