so i have this code which gives me 10 lists, each having 676 dictionaries. these are stored in the variable(bigram_lists)
i want to make 1 list having all the dictionaries then i want to combine the dictionaries with the same key(keeping the key and add up their values)
i tried referencing the lists and dictionaries that are stored in the variable but it didnt work
is there a way to do this? preferably using a for loop and some short commands
CodePudding user response:
Is this what you want to do ?
output = {}
for sublist in bigram_lists:
for dic in sublist:
for key in dic:
output[key] = output.get(key, 0) dic[key]
CodePudding user response:
You can first linearize your lists of dictionaries, then merge together with a for
loop:
d_out = {}
bigrams_linear = sum([list(d.items()) for d in sum(bigrams_lists, [])], [])
for k, v in bigrams_linear:
if k not in d_out:
d_out[k] = 0
d_out[k] = v
d_out
Change your bigram_frenquency
function like this:
def bigram_frequency(taal):
languages = ['dutch', 'english', 'french', 'italian', 'german', 'spanish']
if taal in languages:
bigram_all_lists = []
# gather all data from lists
for i in range(10):
j = i 1
bigram_lists = bigram_frequentie(taal str(j) '.txt')
bigram_all_lists.append(bigram_lists)
#operate on bigram_all_lists
< call previous code here >