python - 如何使用 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'
我可以在没有“地址”字典的情况下插入这个字典,但我对“地址”有问题
解决方案
查询希望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'}
推荐阅读
- python - understanding iteration of python values
- javascript - 如何在javascript中获取自定义谷歌搜索的预填充结果
- html - Why is CSS clear property not clearing floats?
- .net - Open CMD and run command from VB.net
- php - 无法通过身份验证访问 API
- intellij-idea - IntelliJ: custom code generation templates
- managedobjectcontext - Core Data ManagedObjectContext 和 Private Queue,父上下文的作用
- c# - 使用 Natcorder Video 的帧?
- amazon-web-services - AWS - 缓存预定 lambda 函数的响应
- java - Java Lambda 表达式 参数数据类型