Python - Converting nested list into dictionary

前端 未结 1 1792
夕颜
夕颜 2021-01-16 05:06

I have a nested list , how do I convert this into a dictionary

data = [[\"Employee\",\"Salary\",\"Age\",\"Gender\"],[\"001\",1200,25,\"M\"],[\"002\",1300,28,         


        
相关标签:
1条回答
  • 2021-01-16 05:17

    One way is to use zip, which iterates through i th element of each list sequentially:

    data = [["Employee","Salary","Age","Gender"],
            ["001",1200,25,"M"],
            ["002",1300,28,"M"],
            ["003",1400,32,"M"],
            ["004",1700,44,"F"]]
    
    d = {k: v for k, *v in zip(*data)}
    

    Unpacking via *v, as suggested by @Jean-FrançoisFabre, ensures your values are lists.

    Result

    {'Age': [25, 28, 32, 44],
     'Employee': ['001', '002', '003', '004'],
     'Gender': ['M', 'M', 'M', 'F'],
     'Salary': [1200, 1300, 1400, 1700]}
    

    Another way is to use pandas:

    import pandas as pd
    
    df = pd.DataFrame(data[1:], columns=data[0]).to_dict('list')
    
    # {'Age': [25, 28, 32, 44],
    #  'Employee': ['001', '002', '003', '004'],
    #  'Gender': ['M', 'M', 'M', 'F'],
    #  'Salary': [1200, 1300, 1400, 1700]}
    
    0 讨论(0)
提交回复
热议问题