如何将 Excel 的列转换为特定的字典格式?
How can I convert a column of Excel into a specific dictionary format?
我的 excel 文件中有一列,我想将该列的所有行转换为特定的字典格式。
即双引号之间的键和值,括号和圆括号之间的值,在这之前,设置单词,如图:
我使用此代码,但这没有给我想要的格式:
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)
}
您的图像将字典中的值显示为单个值 sets,而不是整数。您可以将 cell.value
放入集合中:
d = {
'item{}'.format(num): {cell.value} for (num, cell) in enumerate(column, 1)
}
检查:
>>> from pprint import pprint
>>> pprint.pprint(d)
{'item1': {5},
'item2': {2},
'item3': {0},
'item4': {1},
'item5': {6},
'item6': {6},
'item7': {1}}
>>> pprint([type(d[key]) for key in d.keys()])
[<class 'set'>,
<class 'set'>,
<class 'set'>,
<class 'set'>,
<class 'set'>,
<class 'set'>,
<class 'set'>]
我的 excel 文件中有一列,我想将该列的所有行转换为特定的字典格式。
即双引号之间的键和值,括号和圆括号之间的值,在这之前,设置单词,如图:
我使用此代码,但这没有给我想要的格式:
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)
}
您的图像将字典中的值显示为单个值 sets,而不是整数。您可以将 cell.value
放入集合中:
d = {
'item{}'.format(num): {cell.value} for (num, cell) in enumerate(column, 1)
}
检查:
>>> from pprint import pprint
>>> pprint.pprint(d)
{'item1': {5},
'item2': {2},
'item3': {0},
'item4': {1},
'item5': {6},
'item6': {6},
'item7': {1}}
>>> pprint([type(d[key]) for key in d.keys()])
[<class 'set'>,
<class 'set'>,
<class 'set'>,
<class 'set'>,
<class 'set'>,
<class 'set'>,
<class 'set'>]