Python按逗号分隔成列表的映射

时间:2018-07-06 11:00:35

标签: python

我的问题与此问题非常相似 Python: split line by comma, then by space

但是我需要向前迈出一步。我的清单实际上看起来像这样

name,phone,monthlysalary,age
Peter,1234567,100000,28
John,22345,200000,30
Mary,32345,300000,40

如果我使用以下方法破坏列表:-

Source="""name,phone,monthlysalary,age
Peter,1234567,100000,28
John,22345,200000,30
Mary,32345,300000,40"""
x = [elem.split(",") for elem in Source.split("\n")]

然后我可以得到如下结果:-

[['name', 'phone', 'monthlysalary', 'age'],
 ['Peter', '1234567', '100000', '28'],
 ['John', '22345', '200000', '30'],
 ['Mary', '32345', '300000', '40']]    

但是我需要的是:-

{'Peter': ['1234567', '100000', '28'],
'John': ['22345', '200000', '30'],
'Mary': ['32345', '300000', '40']}

我想使用列表而不是列表:

  1. 忽略标题行(姓名,电话,月薪,年龄)
  2. 将结果作为列表的字典,以便我可以使用键名找到其详细信息
  3. 如果我能在一行语句中做到这一点将是很棒的,但这是一种修饰

我可以轻松地编写一个简单的代码,如下所示:-

Source="""name,phone,monthlysalary,age
Peter,1234567,100000,28
John,22345,200000,30
Mary,32345,300000,40"""
x = dict()
_, *lines = Source.split("\n")
for line in lines:
    head, *tail = line.split(',')
    x[head] = tail

但是我想知道是否可以使用一个衬板来实现这一目标?

2 个答案:

答案 0 :(得分:3)

这就是CSV模块的作用:

import csv

data = csv.DictReader(filename, delimiter=",")

答案 1 :(得分:0)

如果您不想使用csv模块,则可以像这样复制DictReader的行为:

>>> data = """name,phone,monthlysalary,age
... Peter,1234567,100000,28
... John,22345,200000,30
... Mary,32345,300000,40"""
...
>>> lines = iter(data.splitlines())
>>> head = next(lines).split(",")
>>> [dict(zip(head, line.split(","))) for line in lines]
[{'age': '28', 'monthlysalary': '100000', 'name': 'Peter', 'phone': '1234567'},
 {'age': '30', 'monthlysalary': '200000', 'name': 'John', 'phone': '22345'},
 {'age': '40', 'monthlysalary': '300000', 'name': 'Mary', 'phone': '32345'}]

如果您希望从更新中获取一种格式的结果格式,请尝试以下操作:

>>> {x[0]: x[1:] for x in (line.split(",") for line in data.splitlines()[1:])}
{'John': ['22345', '200000', '30'],
 'Mary': ['32345', '300000', '40'],
 'Peter': ['1234567', '100000', '28']}

但是,导入csv模块的内存消耗和单行代码的好处都可能被高估了。