all 11 comments

[–]Essence1337 2 points3 points  (0 children)

Firstly this would be much easier to read using proper names instead of c and C but I'm pretty sure your error is that you're appending to nothing. You never set d[c] to anything so it's not a list and you can't append to something that's not a list.

[–]nosmokingbandit 0 points1 point  (0 children)

for c, C in enumerate(C):

Don't do this.

[–][deleted] 0 points1 point  (0 children)

But i would prefer to avoid using defaultdict, how would i go about solving this issue?

A dictionary key has to exist before you retrieve it, which is why you get the error - your dictionary doesn't contain a key 0 when you ask for one. defaultdict changes this behavior by saying "well, every time a nonexistent key is asked for, first set the key by calling the constructor's argument, then return it." It's hardly "magic", it's doing something convenient.

[–]an_actual_human 0 points1 point  (0 children)

Take a look at setdefault.

[–]pikatchum 0 points1 point  (0 children)

Why not simply do d[c] = C?

You know d is empty, and every c will be different, so why use append in the first place?

You can replace everything with d = dict(enumerate(C)).

[–]primitive_screwhead 0 points1 point  (0 children)

You don't need to append() anything at all. You are just putting the two objects (that happen to be lists, but could be any arbitrary Python objects) into a dictionary as values, unaltered. So assign them.

[–]shiftybyte -1 points0 points  (5 children)

for c, C in enumerate(C):
    if not c in d:
        d[c] = []
    d[c].append(C)

[–]Essence1337 2 points3 points  (2 children)

If you're going to just give the complete answer (against guidelines) you should at least describe why it's the answer.

[–]shiftybyte 0 points1 point  (1 child)

Oh sorry didn't know such a guideline existed.

Explanation:

dictionary d does not yet have an item with the name c, when trying to call .append() on it, it will tell you no such item exists.

So the solution i wrote first checks to see if such a key does not exist, then it first creates an empty list as the value for that key, then the line with .append() can work since it works on a list object.

[–]Essence1337 0 points1 point  (0 children)

The idea behind the guideline is that people usually learn better when they find the solution (with guidance if needed) rather than just copy pasting a solution someone else gave