将python字节列表转换为字典

时间:2018-07-28 03:46:15

标签: python python-3.x dictionary

我正在尝试将字节列表转换为字典列表

mylist = [b'Ruby,events_spec.rb,188,5,613\n',
b'HTML,index.html,14,0,592\n']

类似

[{'Filename':"events_spec.rb","Language":Ruby","Blank Lines":"188","Comment Lines":"5","Code Lines":613},{'Filename':"index.html","Language":HTML","Blank Lines":"14","Comment Lines":"0","Code Lines":592}]
  

即使“文件名”是列表中的第二个元素,我也想要   “文件名”将成为字典的第一个元素

尝试了一些但没有得到想要的输出

mylist = [b'Ruby,events_spec.rb,188,5,613\n',
b'HTML,index.html,14,0,592\n']

list1 = ["Filename","Language","Blank Lines","Comment Lines","Code Lines"]

final_list = []

n_dict = {}
for i in mylist:
    final_list.append(dict(zip(list1,i.decode("ascii").split(","))))

print(final_list)

不需要的输出

[{'Filename': 'Ruby', 'Language': '/Users/hariomsingh/Desktop/ignit/Repo/ignite-chute-analytics-backend/spec/requests/events_spec.rb', 'Blank Lines': '188', 'Comment Lines': '5', 'Code Lines': '613\n'}, {'Filename': 'HTML', 'Language': '/Users/hariomsingh/Desktop/ignit/Repo/ignite-chute-analytics-backend/docs/index.html', 'Blank Lines': '14', 'Comment Lines': '0', 'Code Lines': '592\n'}

尝试使用OrderedDict

from collections import OrderedDict
mylist = [b'Ruby,/Users/hariomsingh/Desktop/ignit/Repo/ignite-chute-analytics-backend/spec/requests/events_spec.rb,188,5,613\n',
b'HTML,/Users/hariomsingh/Desktop/ignit/Repo/ignite-chute-analytics-backend/docs/index.html,14,0,592\n']


list1 = ["Filename","Language","Blank Lines","Comment Lines","Code Lines"]

final_list = []

n_dict = OrderedDict()
for i in mylist:
        final_list.append(dict(zip(list1,i.decode("ascii").split(","))))

print(final_list)

3 个答案:

答案 0 :(得分:3)

首先,您必须对关键字重新排序以匹配元素在源数据中的位置:

list1 = ["Language","Filename","Blank Lines","Comment Lines","Code Lines"]

那么就这么简单:

mydict = { a : b for a,b in zip( list1, mylist[0].strip().split(',')) }

这给了我们

{'Blank Lines': '188', 'Comment Lines': '5', 'Code Lines': '613', 'Language': 'Ruby', 'Filename': 'events_spec.rb'}

然后您只需要遍历mylist中的所有元素。

答案 1 :(得分:1)

我为您编写了一些代码,您可以尝试

{
  "name": "my-project",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "dependencies": {
    "npm": "^5.6.0"
  },
  "devDependencies": {
    "gulp": "^3.9.1"
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

答案 2 :(得分:1)

您可以使用 re 模块获得更好的输出,因为它可以处理,分隔符之前和之后的空格,而这些分隔符是简单的split()无法做到的。

import re 

mylist = [b'Ruby,events_spec.rb,188,5,613\n',b'HTML,index.html,14,0,592\n']

list1 = ["Language", "Filename", "Blank Lines","Comment Lines","Code Lines"]

final_list = []

for i in mylist:        
    final_list.append(dict(zip(list1,re.split("\s*,\s*", i.decode("ascii").strip()))))

print(final_list)

输出:

[{'Blank Lines': '188', 'Code Lines': '613', 'Filename': 'events_spec.rb', 'Language': 'Ruby', 'Comment Lines': '5'}, {'Blank Lines': '14', 'Code Lines': '592', 'Filename': 'index.html', 'Language': 'HTML', 'Comment Lines': '0'}]