Python将多维列表转字典
今天面试某公司时遇到的一个题目
想想其实很简单的,但是操作起来还是有点难度滴,回来验证了一下自己的代码,没问题
table = [
['Month', 'Day', 'ItemName', 'NumberofItems', 'Price', 'RetailPrice', 'Tax', 'Code', 'SupplierName'],
['01', '01', 'Corporate Creditcard Usage', '', '', '10,364', '1,036', '00140', 'KoreaMcDGangnam'],
['01', '01', 'Corporate Creditcard Usage', '', '', '10,999', '1,101', '00406', 'SpicyChickenBundang'],
['01', '01', 'Corporate Creditcard Usage', '', '', '1,818', '182', '00237', 'PorkBBQItaewon']
]
second_dict = dict()
first_dict=dict()
keys = table.pop(0)
for i in range(len(table)):
for y in range(len(keys)):
second_dict[keys[y]]=table[i][y]
first_dict[str(i)]=str(second_dict)
print(first_dict)
代码结果是
'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
{'0': "{'Month': '01', 'Day': '01', 'ItemName': 'Corporate Creditcard Usage', 'NumberofItems': '', 'Price': '', 'RetailPrice': '10,364', 'Tax': '1,036', 'Code': '00140', 'SupplierName': 'KoreaMcDGangnam'}",
'1': "{'Month': '01', 'Day': '01', 'ItemName': 'Corporate Creditcard Usage', 'NumberofItems': '', 'Price': '', 'RetailPrice': '10,999', 'Tax': '1,101', 'Code': '00406', 'SupplierName': 'SpicyChickenBundang'}",
'2': "{'Month': '01', 'Day': '01', 'ItemName': 'Corporate Creditcard Usage', 'NumberofItems': '', 'Price': '', 'RetailPrice': '1,818', 'Tax': '182', 'Code': '00237', 'SupplierName': 'PorkBBQItaewon'}"}
需要特别注意的点其实就是Python中字典的value其实是一个引用~~~~~~~~~~~
因此在最后保存为大字典时
first_dict[str(i)]=str(second_dict)
不转一下格式的话,因为value是一个引用,它会被后面的数据覆盖,只会得到一组数据,要注意了哦~~~~
本文来自博客园,作者:I'm_江河湖海,转载请注明原文链接:https://www.cnblogs.com/jhhh/p/16761254.html