【问题标题】:Convert numeric data in text file to dictionary [closed]将文本文件中的数字数据转换为字典 [关闭]
【发布时间】:2018-05-08 15:05:09
【问题描述】:

我有一个包含以下内容的文本文件:

20 23
0 16
1 2
1 6
1 7
1 8
2 11
2 16
2 17
3 14
3 16
3 17
4 7
4 13
4 17

我需要它在这样的 python dict 中:

{0:[16],1:[2,6,7,8],2:[11,16,17],3:[14,16,17],4:[7,13,17],20:[23]}

谢谢

【问题讨论】:

  • 您可以使用csv 模块来读取您的数据,并使用collections.defaultsict() 来创建您期望的字典。但最好添加您的代码并告诉我们您的代码有什么问题?
  • @Kasramvd 你的意思是defaultdict()
  • @BlackVegetable NO :-) defaultsict 是 python Easter egg。它可以为您提供您想要的任何格式的字典。但永远不要使用它!因为它可能会导致您的计算机被炸毁,哈哈。
  • @Kasramvd 啊,当然。我忘了那个! ;)

标签: python python-3.x dictionary text


【解决方案1】:

没有声称这是最有效的方式(这只是我想到的方式)我会这样做:

my_dict = {}
with open('input_file_name', 'r') as input_file:
    for line in input_file:
        line = line.strip()
        key = line.split(' ')[0]
        value = line.split(' ')[1]
        my_dict[key] = my_dict.get(key, [])
        my_dict[key].append(value)

然后打印字典:

for key, value in my_dict.items():
    print (key, value)

输出:

4 ['7', '13', '17']
2 ['11', '16', '17']
20 ['23']
1 ['2', '6', '7', '8']
3 ['14', '16', '17']
0 ['16']

但字典没有排序。 但是,您可以在打印字典时对其进行排序:

for key,value in sorted(my_dict.items(), key=lambda x: int(x[0])):
    print (key, value)

请问您是否需要说明每行的含义!

【讨论】:

    【解决方案2】:

    您可以为此使用collections.defaultdict

    下面的完整示例。

    import csv
    from io import StringIO
    from collections import defaultdict
    
    mystr = StringIO("""20 23
    0 16
    1 2
    1 6
    1 7
    1 8
    2 11
    2 16
    2 17
    3 14
    3 16
    3 17
    4 7
    4 13
    4 17
    """)
    
    d = defaultdict(list)
    
    # replace mystr with open('file.csv', 'r')
    with mystr as f:
        for i, j in csv.reader(f, delimiter=' '):
            d[int(i)].append(int(j))
    

    结果:

    print(d)
    
    defaultdict(list,
                {0: [16],
                 1: [2, 6, 7, 8],
                 2: [11, 16, 17],
                 3: [14, 16, 17],
                 4: [7, 13, 17],
                 20: [23]})
    

    【讨论】:

      【解决方案3】:

      你最好用熊猫,

      假设您在 Excel 数据表中有数据

      这个excel文件的目录是

      path = "C:\Users\user\Desktop\python\excel.xlsx"
      
      import pandas as pd
      
      df = pd.read_excel(path)
      
      dictionary = df.groupby("key")["value"].apply(list).to_dict()
      
      print(dictionary)
      
      {0: [16], 1: [2, 6, 7, 8], 2: [11, 16, 17], 3: [14, 16, 17], 4: [7, 13, 17], 20: [23]}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-11-08
        • 1970-01-01
        • 2021-08-07
        • 2020-12-16
        • 2023-03-15
        • 1970-01-01
        相关资源
        最近更新 更多