将大量列表转换为字典和代码仅适用于列表列表中的第一项。
a_list = [[('Bedrooms', ' 4'),
('Street Address', ' 90 Lake '),
('Contact Phone', ' 970-xxx-xxxx'),
('Bathrooms', ' 5'),
('Price', ' $5,350,000'),
('Zip Code', ' 5000')],
[('Bedrooms', ' 4'),
('Street Address', ' 1490 Creek '),
('Contact Phone', ' 970-xxx-xxx3'),
('Bathrooms', ' 10'),
('Price', ' $7,350,000'),
('Zip Code', ' 6000'),
('City', ' Edwards'),
('Price1', ' 4200000')],
[('Street Address', ' 280 Lane'),
('Bedrooms', ' 2'),
('Property Type', ' Townhouse'),
('Square Feet', ' 3000'),
('Bathrooms', ' 4'),
('Contact Phone', ' 303-xxx-xxxx'),
('MLS', ' 66666'),
('Contact Name', ' C Name'),
('Brokerage', ' Real Estate'),
('City', 'Creek'),
('Zip Code', '89899'),
('Price1', ' 2100000'),
('Posted On', ' Nov 13, 2019')
]]
当前代码仅将 k,v 分配给第一项:
items = {}
for line in list:
for i in range(len(line)):
key = line[i][0]
value = line[i][1]
items[key] = value
items.update(line)
结果:
items = {'Bedrooms':' 4'),
('Street Address': ' 90 Lake '),
('Contact Phone': ' 970-xxx-xxxx'),
('Bathrooms': ' 5'),
('Price': ' $5,350,000'),
('Zip Code': ' 5000'}
最终,我想从列表列表中构建匹配键和值的 DataFrame。
最佳答案
有一种更好的方法可以做到这一点,即使用 map
将每个列表转换为字典,然后在其上调用 DataFrame
构造函数。另外,不要使用内置变量作为变量名,在本例中是 list
。我继续将您的输入数据重命名为变量 data
。
dicts = list(map(dict, data))
pd.DataFrame(dicts)
Bathrooms Bedrooms Brokerage ... Square Feet Street Address Zip Code
0 5 4 NaN ... NaN 90 Lake 5000
1 10 4 NaN ... NaN 1490 Creek 6000
2 4 2 Real Estate ... 3000 280 Lane 89899
[3 rows x 14 columns]
关于Python 列表的列表转换为 Dict 到 Dataframe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59330181/