Reputation: 7
I'm attempting to build a dictionary in Python based off the contents of an Excel spreadsheet file. Here is an example of how the spreadsheet is structured (two columns):
Col 1 Col 2
Hello World
Hello Earth
Hello Planet
Hello Mars
Hello Moon
Hi Pluto
Hi Neptune
Hi Jupiter
How do I create a dictionary in Python to make the data look like this:
[{'Hello': 'World', 'Earth', 'Planet', 'Mars', 'Moon'}, {'Hi': 'Pluto', 'Neptune', 'Jupiter'}]
I'm attempting to have each key contain multiple values.
EDIT: changed .csv file to "Excel spreadsheet file"
EDIT2: changed parenthesis to {} in code. sorry, that was an accident.
Upvotes: 0
Views: 246
Reputation: 3739
With Pandas you can do this with:
import pandas as pd
df = pd.read_excel('data1.xlsx')
dictionary = df.to_dict()
Upvotes: 1
Reputation: 336
[{'Hello': 'World', 'Earth', 'Planet', 'Mars', 'Moon'), ('Hi': 'Pluto', 'Neptune', 'Jupiter'}]
is not valid python dictionary. You can't have multiple values for a key.
However, you can have the value as a list of items, like this
{
'Hello': [
'World',
'Earth',
'Planet',
'Mars',
'Moon'
],
'Hi': [
'Pluto',
'Neptune',
'Jupiter'
]
}
Upvotes: 1