如何将一列 Excel 转换为特定的字典格式?

我的 excel 文件中有一个列,我想将该列的所有行转换为特定的字典格式。即双引号之间的keys和values以及括号和圆括号之间的values以及之前的单词设置,如图:

http://img3.mukewang.com/611789ab0001225204930299.jpg

我使用此代码,但这并没有给我我想要的格式:


import openpyxl


# Access active worksheet of excel file

book = openpyxl.load_workbook('workbook.xlsx')

sheet = book.active


# Access first column

column = sheet['A']


# Use dictionary comprehension on the cells in the column

d = {

    'item{}'.format(num): cell.value

    for (num, cell) in enumerate(column, 1)

}


子衿沉夜
浏览 299回答 1
1回答

杨魅力

您的图像将字典中的值显示为单个值集,而不是整数。你可以把它cell.value放到一个集合中:d = {&nbsp; &nbsp; 'item{}'.format(num): {cell.value} for (num, cell) in enumerate(column, 1)}去检查:>>> from pprint import pprint>>> pprint.pprint(d){'item1': {5},&nbsp;'item2': {2},&nbsp;'item3': {0},&nbsp;'item4': {1},&nbsp;'item5': {6},&nbsp;'item6': {6},&nbsp;'item7': {1}}>>> pprint([type(d[key]) for key in d.keys()])[<class 'set'>,&nbsp;<class 'set'>,&nbsp;<class 'set'>,&nbsp;<class 'set'>,&nbsp;<class 'set'>,&nbsp;<class 'set'>,&nbsp;<class 'set'>]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python