Sai Kumar
Sai Kumar

Reputation: 715

how do I write my code using dictionary comprehension?

How can I re-write the last three lines of my code using dictionary comprehension?

The column names for the split2 list is as below.

'year, month, date_of_month, day_of_week, births'

 split2 = [['1994', '1', '2', '7', '7772'],
 ['1994', '1', '3', '1', '10142'],
 ['1994', '1', '4', '2', '11248'],
 ['1994', '1', '5', '3', '11053'],
 ['1994', '1', '6', '4', '11406'],
 ['1994', '1', '7', '5', '11251'],
 ['1994', '1', '8', '6', '8653'],
 ['1994', '1', '9', '7', '7910'],
 ['1994', '1', '10', '1', '10498'],
 ['1994', '1', '11', '2', '11706'],
 ['1994', '1', '12', '3', '11567'],
 ['1994', '1', '13', '4', '11212'],
 ['1994', '1', '14', '5', '11570'],
 ['1994', '1', '15', '6', '8660'],
 ['1994', '1', '16', '7', '8123']]


dayofweek = [int(i[3]) for i in split2]
births = [int(i[-1]) for i in split2]
combine = list(zip(dayofweek, births))
edict = {}
for i in combine:
    if i[0] in edict.keys():
        edict[i[0]] += i[-1]
    else:
        edict[i[0]] = i[-1]
print(edict)

output:
{1: 20640, 2: 22954, 3: 22620, 4: 22618, 5: 22821, 6: 17313, 7: 23805}

Upvotes: 0

Views: 71

Answers (2)

blhsing
blhsing

Reputation: 106552

This will do:

edict = {d: sum(b for w, b in combine if w == d) for d in set(dayofweek)}

Since you want your dict to be based every day of week that has appeared in split2, or a unique set of them, you can iterate over set(dayofweek), and then for a given day of week, generate the dict key on the day and the value being the sum of births of the day by iterating over combine and matching the day and outputting the births of the day with a generator to sum.

Upvotes: 2

Superior
Superior

Reputation: 885

for i in combine:
    edict[i[0]] = edict.get(i[0], 0) + i[1]

but for a more elegant solution, I would do

for i, v in combine:
    edict[i] = edict.get(i, 0) + v

this can be done because elements of combine are of type tuple and by saying "i, v" you automatically unpack it
it is equivalent to saying

for i in combine:
    i, v = i

Upvotes: 0

Related Questions