从 python 中的字典创建 postgres table

Create postgres table from dictionary in python

我正在使用 python 中的 dataset 包连接到本地计算机上的 postgres 数据库。连接后,我 运行 以下代码:

db = dataset.connect('postgresql://user:password@localhost:5432/db')

my_dict = {'Person': ['Joe', 'Lou', 'Kim', 'Tim', 'Emma'], 
           'Age': [40, 37, 13, 8, 3], 
           'Height': ["5'11", "5'6", "5'8", "4'3", "3'0"]}

table = db['new_data']
table.insert(my_dict)

这会在我的本地数据库中创建一个名为 new_data 的 table,但结果是这样的:

 id |             Person             |      Age       |         Height        
----+--------------------------------+----------------+------------------------
  1 |      {Joe,Lou,Kim,Tim,Emma}    | {40,37,13,8,3} | {5'11,5'6,5'8,4'3,3'0}

基本上,我的字典项的所有值都返回到同一行。这应该与每个项目有不同的行,类似于数据框。

    Person  Age Height
0   Joe     40  5'11
1   Lou     37  5'6
2   Kim     13  5'8
3   Tim     8   4'3
4   Emma    3   3'0

我结合了我尝试过的东西:

我手动创建了字典 {k:v}。当我传递该对象以将其插入 table 时,这会起作用,但它会使行不正确,如您在上面看到的那样。我还尝试使用 to_dict 函数,从 pandas DataFrame 创建字典,但出现以下错误:

ProgrammingError: (psycopg2.ProgrammingError) can't adapt type 'dict'

这似乎与使用 to_dict 函数时 dictionary 项目的创建方式有关,因为键是列名,但值是嵌套字典,与行索引作为键,行值作为值。

我尝试的另一件事是使用字典理解创建字典,迭代数据框。我得到与上面相同的错误。我不知道如何解决这个问题。

假设 dict 中的所有键长度相等,您可以将上面的字典转换为以下形式。

[{'Person': 'Joe', 'Age': 40, 'Height': "5'11"},
 {'Person': 'Lou', 'Age': 37, 'Height': "5'6"},
 {'Person': 'Kim', 'Age': 13, 'Height': "5'8"},
 {'Person': 'Tim', 'Age': 8, 'Height': "4'3"},
 {'Person': 'Emma', 'Age': 3, 'Height': "3'0"}]

现在您可以迭代每个 dict 对象并将其插入到您的 table 中,如下所示,

for pos, val in enumerate(my_dict['Person']):
    table.insert({'Person': val, 'Age': my_dict['Age'][pos], 'Height': my_dict['Height'][pos]})