【问题标题】:python: convert below format type of list in to dictionarypython:将以下格式类型的列表转换为字典
【发布时间】:2016-12-01 11:04:56
【问题描述】:

我想将以下类型的列表转换为字典:

input_list = [' test1                                  0', ' test2                     1']

output_dict = {'test1': 0, 'test2': 1}

如果我输入上面的列表,期望以字典的形式输出。问题是输入列表在对象中有空格。例如。 test1 和 0 之间有很多空格

【问题讨论】:

标签: python list dictionary


【解决方案1】:

只是一个想法,未经测试;)

output_dict = {}
for item in input_list:
  kye, value = item.split()
  output_dict[kye] = value

【讨论】:

    【解决方案2】:

    使用split 从数据中获取键和值。

    for string in input_list:
        key,value = filter(lambda s: len(s)>0,string.split(' '))
        output_dict[key] = int(value)
    print output_dict
    

    【讨论】:

      【解决方案3】:

      拆分字符串得到两个项目,第一个是字典的键,第二个是值。

      代码如下:

      input_list = [' test1                                  0', ' test2                     1']
      output_dict = dict()
      for single_item in input_list:
          single_item = single_item.strip()
          single_item_ar = single_item.split()
          output_dict[single_item_ar[0]] = int(single_item_ar[1])
      print(output_dict)
      

      输出:

      {'test1': 0, 'test2': 1} 
      

      注意:此操作可以通过多种方式完成。这是最简单和人类可读的方式。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-23
        • 1970-01-01
        • 2023-03-10
        • 2013-06-07
        • 2019-02-10
        • 1970-01-01
        相关资源
        最近更新 更多