0
items = ['1', '2', '3']
for item in items:
   df_list[item]= df.loc[file_df['Item'] == item]

This works fine. However if my item list is something else, for example:

items = [{'code': '1', 'other_needed_value': 1}, {'code': '2', 'other_needed_value': 2}, {'code': '3', 'other_needed_value': 3}]
for item in items:
    code = item['code']
    df_list[item]= df.loc[file_df['Item'] == code]

Obviously I'm comparing file_df['Item'] to a string, however I get this error from pandas

unhashable type: 'dict'

How should I solve this issue? Thanks in advance.

4
  • Is your list of dictionaries called item or is this a typo? Also it'd be good to put the full Traceback error so we can see which line is causing the problem Commented Nov 10, 2021 at 4:02
  • Sorry it's a typo while changing the variable names. Will edit Commented Nov 10, 2021 at 4:04
  • The problem isn't the comparison. The problem is trying to use item as a dict key, when item is itself a dict. If you meant to use code as the dict key, then that's just a typo. Otherwise please refer to the linked duplicate. Commented Nov 10, 2021 at 4:25
  • In the future, you should also try to debug your code first before asking. This starts by trying to understand the error message; in particular, what part of that line of code causes the error. You may find it helpful to break that line up into smaller parts. In this case, for example, you might have assigned df.loc[file_df['Item'] == code] to a temporary variable first, before assigning that to df_list[item]. You would have immediately seen that the problem was in the second part. Commented Nov 10, 2021 at 4:27

2 Answers 2

2

df_list[item] should be df_list[code]. What's happening here is that the list df_list is being indexed with item which, in the 2nd code example above, is actually a dictionary, hence the error. What OP wants is to take the 'code' value of the dictionary. The desired code can also be written as:

for item in items:
    df_list[item['code']]= df.loc[file_df['Item'] == item['code']]
Sign up to request clarification or add additional context in comments.

1 Comment

No worries. In the future, if you encounter this type of error and aren't sure which variable is causing the problem, you can always try debugging by setting a breakpoint in the code where the error is being thrown and then examining which variable is a dictionary. Here's a tutorial on how to do that in VSCode
0

I am not able to run your code, but i see that you use

for item in items:
    code = item['code']

what is the type of item it seems it is a dictionary because in the next line you use item['code'] ==> hence a dictionary maybe you were trying to assign df_list[code]?

little more code/output would help

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.