Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way of executing a loop on a dictionary of lists

Tags:

python

loops

This code works but I was wondering if there is a more pythonic way for writing it.

word_frequency is a dictionary of lists, e.g.:

word_frequency = {'dogs': [1234, 4321], 'are': [9999, 0000], 'fun': [4389, 3234]}

vocab_frequency = [0, 0] # stores the total times all the words used in each class
for word in word_frequency: # that is not the most elegant solution, but it works!
    vocab_frequency[0] += word_frequency[word][0] #negative class
    vocab_frequency[1] += word_frequency[word][1] #positive class

Is there a more elegant way of writing this loop?

like image 835
Victor Zuanazzi Avatar asked Nov 09 '18 13:11

Victor Zuanazzi


4 Answers

I'm not sure if this is more Pythonic:

>>> word_frequency = {'dogs': [1234, 4321], 'are': [9999, 0000], 'fun': [4389, 3234]}
>>> vocab_frequency = [sum(x[0] for x in word_frequency.values()),
                       sum(x[1] for x in word_frequency.values())]
>>> print(vocab_frequency)
[15622, 7555]

Alternate solution with reduce:

>>> reduce(lambda x, y: [x[0] + y[0], x[1] + y[1]], word_frequency.values())
[15622, 7555]
like image 178
hochl Avatar answered Oct 15 '22 07:10

hochl


You could use numpy for that:

import numpy as np

word_frequency = {'dogs': [1234, 4321], 'are': [9999, 0000], 'fun': [4389, 3234]}
vocab_frequency = np.sum(list(word_frequency.values()), axis=0)
like image 22
David Speck Avatar answered Oct 15 '22 07:10

David Speck


list(map(sum, zip(*word_frequency.values())))
like image 35
drhodes Avatar answered Oct 15 '22 06:10

drhodes


Probably not the shortest way to solve this, but hopefully the most comprehensible...

word_frequency = {'dogs': [1234, 4321], 'are': [9999, 0000], 'fun': [4389, 3234]}

negative = (v[0] for v in word_frequency.values())
positive = (v[1] for v in word_frequency.values())
vocab_frequency = sum(negative), sum(positive)

print (vocab_frequency)  # (15622, 7555)

Though more experienced Pythonistas might rather use zip to unpack the values:

negative, positive = zip(*word_frequency.values())
vocab_frequency = sum(negative), sum(positive)
like image 40
Sebastian Loehner Avatar answered Oct 15 '22 05:10

Sebastian Loehner