-3

I am trying to create dictionary from a pandas data-frame of the users for the books that the user has read.

User Book
user1 book1
user 2 book1
user1 book2
user1 book3
user2 book3
user2 book2

Expected result:

{
    user1: book 1, book2, book3...
    user2: book1, book3, book2...
    ...
}
Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
  • 1
    You could have searched Stack Overflow and found that duplicate and many others, or even just looked at [the documentation](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_dict.html) – ddejohn Feb 25 '22 at 04:57
  • You can see in Stack Overflow and found that duplicate questions. – Salio Feb 25 '22 at 05:00
  • `d = df.groupby('User')['Book'].agg(list).to_dict()` like [this answer](https://stackoverflow.com/a/29876239/15497888) seems like what you're looking for. – Henry Ecker Feb 25 '22 at 05:12

1 Answers1

0

Use loc to find users based on unique values:

total_users = list(df['User'].unique())  #find unique users

final_dict = {}
for usr in total_users:
    final_dict[usr] = df.loc[df['User']==usr,'Book'].tolist()
print(final_dict)
Prakash Dahal
  • 4,388
  • 2
  • 11
  • 25