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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值