首页 > 解决方案 > 如何使用 Python 将嵌套字典添加到 PostgreSQL?

问题描述

我有一个字典,我不知道它是不是嵌套字典。我的字典是:

my_dict = {"username": "XYZ", "email": "xyz@gmail.com",
           "location": "Mumbai", "Address": {"Country": "", "City": "", "Street": ""}}

我添加了两个这样的值:

my_dict['name'] = []
my_dict['number'] = []

最后我想将此字典添加到 Postgresql 表中。表格是:

在此处输入图像描述

我的完整代码是:

my_dict = {"username": "XYZ", "email": "xyz@gmail.com",
           "location": "Mumbai", "Address": {"Country": "", "City": "", "Street": ""}}

my_dict['name'] = []
my_dict['number'] = []

my_dict["name"] = 'Test'
my_dict["number"] = 30
my_dict["Address"]["Country"] = "Turkey"
my_dict["Address"]["City"] = "Istanbul"
my_dict["Address"]["Street"] = "221sk"


cursor_connection.execute(
    '''INSERT into test_table VALUES (%(username)s, %(email)s , %(location)s, %(Country)s , %(City)s , %(Street)s , %(name)s , %(number)s);''', my_dict)
connection_db.commit()

我收到了这个错误:

KeyError: 'Country'

我可以在没有“地址”字典的情况下插入这个字典,但我对“地址”有问题

标签: pythonpostgresqldictionary

解决方案


查询希望Country在第一级的字典中找到 a ,但这里没有。

我建议你创建一个新的字典,将Address值设置在第一级

values = {**my_dict, **my_dict['Address']}
del values['Address']

cursor_connection.execute(
    '''INSERT into test_table VALUES (%(username)s, %(email)s , %(location)s, %(Country)s , %(City)s , %(Street)s , %(name)s , %(number)s);''', values)
connection_db.commit()


# my_dict
{'username': 'XYZ', 'email': 'xyz@gmail.com', 'location': 'Mumbai', 'name': 'Test',
 'Address': {'Country': 'Turkey', 'City': 'Istanbul', 'Street': '221sk'}, 'number': 30}

# values
{'username': 'XYZ', 'email': 'xyz@gmail.com', 'location': 'Mumbai', 'name': 'Test', 
  'number': 30, 'Country': 'Turkey', 'City': 'Istanbul', 'Street': '221sk'}

推荐阅读