我有以下列表
lines =
[['client', 'name', 'phone', 'address', 'email'],
['client2', 'name2', 'phone2', 'address2', 'email2'],
['client3', 'name3', 'phone3', 'address3', 'email3']]
我想知道是否可以将列表转换为dic列表。
像:
lines =
[{Client: client, Name:name, Phone:phone, Address:address, Email:email},
{Client: client2, Name:name2, Phone:phone2, Address:address2, Email:email2},
{Client: client3, Name:name3, Phone:phone3, Address:address3, Email:email3}]
答案 0 :(得分:1)
提供“行”是一个列表列表,你可以把它变成一个字典列表,如下所示:
clientList = []
for line in lines:
clientList.append({'Client':line[0],
'Name':line[1],
'Phone':line[2],
'Address':line[3],
'Email':line[4]})
答案 1 :(得分:0)
根据您的评论,这是我认为您想要的。首先,您需要列出所有密钥的名称:
>>> keys = ["Client", "Name", "Phone", "Address", "Email"]
然后,很容易从包含密钥项目的列表转到dict:
>>> info_list = ["Client #1", "Joe", "800-213-4445", "123 Fake St.", "fake@fake.com"]
>>> dict(zip(keys, info_list))
{'Email': 'fake@fake.com', 'Phone': '800-213-4445', 'Client': 'Client #1', 'Name': 'Joe', 'Address': '123 Fake St.'}
现在,如果您有36个项目,那么您只需要36个密钥列表。
答案 2 :(得分:0)
一个开始:
lines = [client, name, phone, address, email,
client2, name2, phone2, address2, email2,
client3, name3, phone3, address3, email3]
linesD = {entry: entry for entry in lines}
答案 3 :(得分:0)
你不能用它们制作一个单独的字典,但你可以制作一个字典列表 - 这就是我要做的:
lines = [
client, name, phone, address, email,
client2, name2, phone2, address2, email2,
client3, name3, phone3, address3, email3,
]
keys = ('Client', 'Name', 'Phone', 'Address', 'Email')
clients = [dict(zip(keys, lines[i:i+5])) for i in xrange(0, len(lines), 5)]
答案 4 :(得分:0)
因为你的数据格式不好,我稍微改了一下......
import pandas as pd
...
lines = [
[client, name, phone, address, email],
[client2, name2, phone2, address2, email2],
[client3, name3, phone3, address3, email3]]
fields=["Client", "Name", "Phone", "Address", "Email"]
s = pd.DataFrame(lines, columns=fields)
# choose one u want:
print(list(s.T.to_dict().values())
print(s.to_dict(outtype='list'))
print(s.T.to_dict())