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)

代码结果是

{'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是一个引用,它会被后面的数据覆盖,只会得到一组数据,要注意了哦~~~~

有更好解决方案的大佬可以留言,因为我自己感觉这个实现用了两个遍历,还是有点麻烦

猜你喜欢

转载自www.cnblogs.com/oslo254804746/p/12064153.html