如何将列表对象转换为python dict

时间:2019-01-15 19:58:02

标签: python list dictionary

我有一个简单的python列表,需要将其转换为字典。但是,键和值在列表的每个元素中。如何隔离它们,以便仅使用它们的键就可以提取元素?

    # read the input from a text file (for example)
    lines = open("test.txt").readlines()

    f1 = []
    for x in range(0, len(lines)):
         score = lines[x].rstrip()
         if "metric" in score:
            f1.append(score)
         if "target" in score:
            f1.append(score)
   print(f1)

   >> ['       "metric": "ACCURACY",', '       "target": "match",']

    f1_dict = json.loads('{' + f1[] + '}')
    print(f1_dict)

我正在解析的文件:

  INFO:root: file exists and is readable.
  INFO:root:Header is valid. output/twst.csv scores=[ { 
             "metric": "ACCURACY", 
             "target": "match",   
  }]

错误:

  

json.decoder.JSONDecodeError:期望的属性名称包含在其中   双引号:第1行第30列(字符29)

我如何轻松做到这一点?

0 个答案:

没有答案
相关问题