创建一个词典列表

时间:2017-07-09 07:22:19

标签: python list dictionary

我的解决方案

keys = ['FirstName', 'LastName', 'ID']

name1 = ['Michael', 'Jordan', '224567']
name2 = ['Kyle', 'Hynes', '294007']
name3 = ['Josef', 'Jones', '391107']

dictList = []
dictList.append(dict(zip(keys, name1)))
dictList.append(dict(zip(keys, name2)))
dictList.append(dict(zip(keys, name3)))

for item in dictList:
    print(' '.join([item[key] for key in keys]))

工作正常,但还有其他任何解决方案,因为我将至少有20000个名字,所以我正在寻找如何改进这个。

Michael Jordan 224567
Kyle Hynes 294007
Josef Jones 391107

4 个答案:

答案 0 :(得分:3)

你真的需要一本字典吗?为什么不使用namedtuple

>>> from collections import namedtuple
>>> Employee = namedtuple('Employee', 'FirstName, LastName, ID')
>>> names_list = [['Michael', 'Jordan', '224567'], ['Kyle', 'Hynes', '294007'], ['Josef', 'Jones', '391107']]
>>> employee_list = map(Employee._make, names_list)
>>> employee_list[0].FirstName
'Michael'
>>> pprint(employee_list)
[Employee(FirstName='Michael', LastName='Jordan', ID='224567'),
 Employee(FirstName='Kyle', LastName='Hynes', ID='294007'),
 Employee(FirstName='Josef', LastName='Jones', ID='391107')]

答案 1 :(得分:3)

将所有“名称”子列表放入列表names。然后你可以轻松使用列表理解:

keys = ['FirstName', 'LastName', 'ID']
names = [
    ['Michael', 'Jordan', '224567'],
    ['Kyle', 'Hynes', '294007'],
    ['Josef', 'Jones', '391107']
]

dictList = [{k:v for k,v in zip(keys, n)} for n in names]
print(dictList)

输出:

[{'FirstName': 'Michael', 'LastName': 'Jordan', 'ID': '224567'}, {'FirstName': 'Kyle', 'LastName': 'Hynes', 'ID': '294007'}, {'FirstName': 'Josef', 'LastName': 'Jones', 'ID': '391107'}]

答案 2 :(得分:1)

您应该将字典附加到循环内的列表中,如下所示:

In [1152]: names = [name1, name2, name3]

In [1153]: d = []

In [1154]: for name in names:
      ...:     d.append(dict(zip(keys, name)))
      ...:     

In [1155]: d
Out[1155]: 
[{'FirstName': 'Michael', 'ID': '224567', 'LastName': 'Jordan'},
 {'FirstName': 'Kyle', 'ID': '294007', 'LastName': 'Hynes'},
 {'FirstName': 'Josef', 'ID': '391107', 'LastName': 'Jones'}]

或者,如果您愿意,可以使用列表理解:

In [1160]: d = [dict(zip(keys, name)) for name in names]

In [1161]: d
Out[1161]: 
[{'FirstName': 'Michael', 'ID': '224567', 'LastName': 'Jordan'},
 {'FirstName': 'Kyle', 'ID': '294007', 'LastName': 'Hynes'},
 {'FirstName': 'Josef', 'ID': '391107', 'LastName': 'Jones'}]

答案 3 :(得分:0)

熊猫太容易了。

import pandas as pd

keys = ['FirstName', 'LastName', 'ID']
name1 = ['Michael', 'Jordan', '224567']
name2 = ['Kyle', 'Hynes', '294007']
name3 = ['Josef', 'Jones', '391107']

doc_list = [name1,name2,name3]
df = pd.DataFrame(doc_list,columns = keys)

所以你将拥有一个像这样的DataFrame:

   FirstName  LastName   ID
0   Michael   Jordan  224567
1      Kyle    Hynes  294007
2     Josef    Jones  391107

如果您的名字已经在文件中,read_csv会更好。

pd.read_csv("file_name.csv",header=keys)//remove the header parameter if it is present in your csv.