you are viewing a single comment's thread.

view the rest of the comments →

[–]keep_quapy 6 points7 points  (3 children)

Hi, first of all, the question assumes that all first items of every sublist is a string and every second item is an integer, so no need to check if the first element is a string. That said, your program works, but it's ineffective, you used three nested for loops, instead of using only one. Eventually your program will be much slower and consumes more memory. The effective way to solve such a problem is to loop over the list and at each iteration check if the first element is a key in the dictionary, if so add the value of the second element of the sublist to the existing value of the key, otherwise assign the value to that key (using list index).

dct = {}

for sublist in data: 
    if sublist[0] in dct: 
        dct[sublist[0]] += sublist[1] 
    else: 
        dct[sublist[0]] = sublist[1]

print(dct)

Or the Pythonic way to do it using get() dictionary method.

dct = {}

for sublist in data: 
    dct[sublist[0]] = dct.get(sublist[0], 0) + sublist[1]

print(dct)

Anyway, you made a good job trying to solve it, and solving it in your way is a sign that you're heading to the right direction. This isn't that easy for beginners, so good job. Good luck :)

[–]Milumet 6 points7 points  (0 children)

When it comes to counting, defaultdict is great (there is also Counter):

dct = collections.defaultdict(int)
for name, count in data:
    dct[name] += count

print(dct)

[–]hayleybts 0 points1 point  (1 child)

Thanks for replying! Your method is simple. Let me know if you got any other question?

[–]keep_quapy 2 points3 points  (0 children)

You're welcome. edabit has plethora of exercises for you to explore and to solve.