【问题标题】:Create postgres table from dictionary in python从python中的字典创建postgres表
【发布时间】:2019-08-20 20:24:28
【问题描述】:

我在 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 的表,但结果如下:

 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}。这在我传递该对象以将其插入表时有效,但它会使行不正确,如您在上面看到的。我也尝试使用 to_dict 函数,从 pandas DataFrame 创建字典,但出现以下错误:

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

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

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

【问题讨论】:

  • 我正在将您的代码输入到空的 python 文件中。节省。跑。它只是工作;)

标签: python sql postgresql dataset psycopg2


【解决方案1】:

假设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 对象并将其插入到您的表中,如下所示,

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

【讨论】:

    猜你喜欢
    • 2017-05-05
    • 2013-10-26
    • 1970-01-01
    • 2021-06-25
    • 2014-11-11
    • 2020-11-17
    • 2018-04-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多