-2

我有以下列表

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}]
4

5 回答 5

1

提供“行”是一个列表,你可以把它变成一个字典列表,像这样:

clientList = []
for line in lines:
    clientList.append({'Client':line[0],
                       'Name':line[1], 
                       'Phone':line[2], 
                       'Address':line[3], 
                       'Email':line[4]})
于 2013-10-04T15:18:43.097 回答
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)]
于 2013-10-04T15:48:00.450 回答
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 个键的列表。

于 2013-10-04T15:18:32.533 回答
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())
于 2013-10-04T16:02:11.860 回答
0

一个开始:

lines = [client, name, phone, address, email,
         client2, name2, phone2, address2, email2,
         client3, name3, phone3, address3, email3]

linesD = {entry: entry for entry in lines}
于 2013-10-04T15:25:51.683 回答