Python 列表列表转换为字典到数据框

Python Lists of Lists Converting to Dict to Dataframe

将大量列表列表转换为字典和代码仅适用于列表列表中的第一项。

a_list = [[('Bedrooms', ' 4'),
  ('Street Address', ' 90 Lake '),
  ('Contact Phone', ' 970-xxx-xxxx'),
  ('Bathrooms', ' 5'),
  ('Price', ' ,350,000'),
  ('Zip Code', ' 5000')],

  [('Bedrooms', ' 4'),
  ('Street Address', ' 1490 Creek '),
  ('Contact Phone', ' 970-xxx-xxx3'),
  ('Bathrooms', ' 10'),
  ('Price', ' ,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': ' ,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]

是这样的吗?

unpacked = [{k: v for k,v in one_list} for one_list in list_of_lists]
pd.DataFrame(unpacked)

python中的字典是一种存储键值对的数据结构。本质上,每次向字典添加键值对(使用更新)时,都需要一个唯一键。它执行以下操作:

  1. 检查密钥是否存在
  2. 如果键存在,它会将值更新为新值
  3. 如果它们的键不存在,它会将键值对添加到字典中

你可以看看这个 link 以便更好地理解 'update'

https://python-reference.readthedocs.io/en/latest/docs/dict/update.html

尽管有更简单的方法可以做到这一点,但您的代码的问题在于最后一行,即

items.update(line)

您可以使用下面的代码代替您的代码(如果您选择继续使用相同的方法,而不是其他答案建议的方法):

items = {}
new_list = [] # another list
for line in list:
    for i in range(len(line)):
        key = line[i][0]
        value = line[i][1]
        items[key] = value
    new_list.append(items) # use this line instead of your update

然后

import pandas as pd
pd.DataFrame(new_list)

这应该会给您想要的结果。