Python 如何将Excel列转换为特定的字典格式?
我的excel文件中有一列,我想将该列的所有行转换为特定的字典格式。 也就是说,双引号之间的键和值以及括号和圆括号之间的值,在此之前,设置单词,如图所示: 我使用此代码,但它没有提供我想要的格式:Python 如何将Excel列转换为特定的字典格式?,python,dictionary,openpyxl,Python,Dictionary,Openpyxl,我的excel文件中有一列,我想将该列的所有行转换为特定的字典格式。 也就是说,双引号之间的键和值以及括号和圆括号之间的值,在此之前,设置单词,如图所示: 我使用此代码,但它没有提供我想要的格式: import openpyxl # Access active worksheet of excel file book = openpyxl.load_workbook('workbook.xlsx') sheet = book.active # Access first column colu
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)
}
您的图像将字典中的值显示为单个值,而不是整数。您可以将
单元格.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'>]
>>从pprint导入pprint
>>>pprint.pprint(d)
{'item1':{5},
'item2':{2},
'item3':{0},
'item4':{1},
'项目5':{6},
'item6':{6},
'item7':{1}
>>>pprint([type(d[key])表示d.key()中的key)
[,
,
,
,
,
,
]
非常感谢Orix。很高兴我的回答对您有所帮助。:)如果你不介意,请接受我的回答,并将这个问题标记为已解决