0

I have got a data-frame with the following values:

Location   ID
DS         12973
DS         12955
DS         12947
St. paul   12949
Bakersfield 12097
Vernon     12905
vernon     12096
vernon     12902

and so on

I want to convert it into a dictionary in the following way, can anyone please help:

{
'DS':[12973, 12955, 12947]
'St.Paul':[12949, 12955]
'Bakersfield, CA': [ 12097]
'Vernon': [12905, 12906, 12902, 12927, 12900, 12915]
}
Akshay Sehgal
  • 18,741
  • 3
  • 21
  • 51
aman varma
  • 11
  • 4
  • Maybe [this](https://stackoverflow.com/questions/26716616/convert-a-pandas-dataframe-to-a-dictionary) will help? – Rashid 'Lee' Ibrahim Aug 28 '20 at 17:42
  • I tried that but it doesnt work for me – aman varma Aug 28 '20 at 17:44
  • 1
    @amanvarma - People here take a lot of time out from their own schedules to assist others on SO, A good way to thanks & support any help you receive on SO is to upvote/mark the correct answer on your question. This not only motivates them to continue helping but also lets others, who face similar question, get a the right solution. – Akshay Sehgal Aug 29 '20 at 03:11

2 Answers2

2

Try this (groupby location and get ID as a list, then convert to dict)-

df['Location'] = df['Location'].str.lower() #This is because Vernon and vernon both exist, one with a capital V and another with a lower case v.

df.groupby('Location')['ID'].apply(list).to_dict()
{'bakersfield': [12097],
 'ds': [12973, 12955, 12947],
 'st. paul': [12949],
 'vernon': [12905, 12096, 12902]}
Akshay Sehgal
  • 18,741
  • 3
  • 21
  • 51
0

another way to solve this is to use groupby

df['Location'] = df.Location.str.lower()
{loc: list(grp.ID) for loc, grp in df.groupby('Location')}
acushner
  • 9,595
  • 1
  • 34
  • 34