TypeError: '<' not supported between instances of 'int' and 'str'

Hello everyone,

On executing exercise 3, I am getting this error every time. And the indicated line is pre-defined in the notebook.
Please help me to rectify this error.

2 Likes

Hey, I’m not sure if you’re still having this error, but this means you’ve not initialized the dictionaries properly and used some integer as a tag rather than the ones you should have used. Please recheck UNQ_C1.

For me, this error wasn’t that simple. I was only getting the error after the second time I’d run UNQ_C3. That told me tag_counts was being modified during UNQ_C3 even though it was never specifically changed.

I had an error where I’d put tag_counts[i] instead of tag_counts[all_tags[i]] (or something like that).

Because tag_counts is a defaultdict, it saw tag_counts[1] and created the key 1 with the default value of 0.

Running UNQ_C3 the second time, the sorting function sees some string keys and some int keys and throws the error here.

Hope that helps anyone looking at this in the future. =)

10 Likes

Totally agree with Vincent. As explained, always use tag_counts[all_tags[i]] rather than tag_counts[i] as the latter one will not only get execution error but also lead to unexpected results.

Like @Vincent_Rupp says create_transition_matrix modifies tag_counts.

I solved it using:

A = create_transition_matrix(alpha, tag_counts.copy(), transition_counts)

Also agree - helped me thanks @Vincent_Rupp suggestion worked

Same problem nothing changed, any new solution? I try all the solutions that I found here but nothing changed

thanks a ton! was stuck on this forever

Dangers of using defaultdict, you can accidentally assign new indexes with different types :slightly_smiling_face:

I used “count_prev_tag = tag_counts[all_tags[i]]” instead of “count_prev_tag = tag_counts[i]” . It worked . Thanks @Vincent_Rupp

I ran into this issue as well. So the issue is this - any time anywhere above in your code do this: tag_counts[i] - it adds a new key to your tag_counts dictionary, i, if it does not exist (and of course it does not exist, as it is just an index!). So you rerun the cell. And thus your tag_counts is updated. This is because we use defaultdict, not just dict. And if you have, for example i=0, it adds 0 as a key, as it does not exist there. Then suddenly your tag_counts dictionary has integer keys, besides the string ones. So in principle, you don’t need to do anything, if your code is right. If not, avoid using tag_counts[i].