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是一個引用,它會被后面的數據覆蓋,只會得到一組數據,要注意了哦~~~~

有更好解決方案的大佬可以留言,因為我自己感覺這個實現用了兩個遍歷,還是有點麻煩


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM