简体   繁体   English

Excel文件转Python字典

[英]Excel file to Python dictionary

I have an Excel table where Column A is a list of emails and column B is a customer ID. 我有一个Excel表,其中A列是电子邮件列表,B列是客户ID。

I need to create a Python dictionary and have key=email address and value = customer ID . 我需要创建一个Python字典,并具有key=email addressvalue = customer ID

Desired results: 所需结果:

dict = {email@domain.com :'customer ID'}

My code is below: 我的代码如下:

import pandas as pd
excel = "excel_file.xlsx"
list_dict = pd.read_excel(excel, index_col=0).to_dict()
print list_dict

However the dictionary is printing like this: 但是,字典是这样打印的:

{u'customer ID': {u'email@domain.com': u'customer ID}}

What am I doing wrong here? 我在这里做错了什么?

If your excel file looks like this: 如果您的excel文件如下所示:

在此处输入图片说明

Then you could do: 然后,您可以执行以下操作:

import pandas as pd
excel = "excel_file.xlsx"
list_dict = pd.read_excel(excel, header=None).to_dict('list')
print {k: v for k, v in zip(*list_dict.values())}

(tested on Python3, im sure it works in Python2 as well -> be careful about Unicode) (在Python3上进行了测试,请确保它也可以在Python2中使用->注意Unicode)

Output: 输出:

C:\projects\python\test\so_pandas_dict>python main.py
{'example@gmail.com': 'customer ID', 'example1@gmail.com': 'customer ID1'}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM