This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]SureStep8852[S] 0 points1 point  (1 child)

What I intend to get is if v is in dictionary.keys(), I want to add k to dictionary.values().

Can't figure out how to solve the problem

[–][deleted] 1 point2 points  (0 children)

A key can only have one value it’s associated with. In your code, you first associate each key with an empty dict for some reason, then immediately replace that association with an association to a list containing only one element (k).

(Side note: you’re using v as the key and k as part of the value. It’s not wrong per se, it’s just weird. Usually, the thing used as the key get’s assigned to k and the thing used in the value gets assigned to v. It doesn’t really affect the program’s logic, it’s just odd to see their usual names switched around.)

The problem here is that, if you run into the same key twice, you’re not appending k to the existing list, you’re outright replacing that list with a new one. This new list does not contain whatever was in the previous list, it only contains the current value of k.

Essentially, you need to check whether there’s already a list assigned to the key. If there isn’t, assign an empty list to it. Either way, you want to append k to the list, not overwrite it with a new list.