How to create a dictionary of the contents of an E

2019-09-16 14:37发布

问题:

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.

回答1:

[{'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'
    ]
}


回答2:

With Pandas you can do this with:

import pandas as pd
df = pd.read_excel('data1.xlsx')
dictionary = df.to_dict()