首页 文章

如何从CSV中创建一个包含两列的字典作为Python中的键[duplicate]

提问于
浏览
3

这个问题在这里已有答案:

我正在尝试从具有3列的CSV创建字典,其中前两列成为键,第三列成为值:

在此示例中,example.csv包含:

Column-1    Column-2   Column-3
1           A          foo
2           B          bar

预期产量应为:

dictionary = {1, A: foo, 2, B: bar}

我目前正在尝试从pandas数据框导入并转换为字典 . 我使用以下不成功:

df = pd.read_csv("example.csv")
dictionary = df.set_index(['Column-1', 'Column-2']).to_dict()

有没有办法使用pandas来创建字典或是否有更优雅的方式将csv转换为字典?

2 回答

  • 2

    您已接近IIUC - 需要按 ['Column-3'] 选择列:

    d = df.set_index(['Column-1', 'Column-2'])['Column-3'].to_dict()
    print (d)
    {(2, 'B'): 'bar', (1, 'A'): 'foo'}
    
  • 4

    选项1

    dict(zip(zip(df['Column-1'], df['Column-2']), df['Column-3']))
    
    {(1, 'A'): 'foo', (2, 'B'): 'bar'}
    

    选项2

    {(a, b): c for a, b, c in df.values}
    
    {(1, 'A'): 'foo', (2, 'B'): 'bar'}
    

相关问题