Shadi
Shadi

Reputation: 313

How to add a nested dictionary to PostgreSQL with Python?

I have a dictionry, I don't know it's a nested dict or no. My dictionary is:

my_dict = {"username": "XYZ", "email": "[email protected]",
           "location": "Mumbai", "Address": {"Country": "", "City": "", "Street": ""}}

I addedd two values like this:

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

and finaly I want to add this dict to Postgresql table. The table is:

enter image description here

My full code is:

my_dict = {"username": "XYZ", "email": "[email protected]",
           "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()

I received this error:

KeyError: 'Country'

I can insert this dict without "Address"'s dictionary but I have a problem with "Address"

Upvotes: 1

Views: 639

Answers (1)

azro
azro

Reputation: 54168

The query expects to find a Country in the dict at first level, but here isn't.

I'd suggets you create a new dict, with setting the Address values at first level

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': '[email protected]', 'location': 'Mumbai', 'name': 'Test',
 'Address': {'Country': 'Turkey', 'City': 'Istanbul', 'Street': '221sk'}, 'number': 30}

# values
{'username': 'XYZ', 'email': '[email protected]', 'location': 'Mumbai', 'name': 'Test', 
  'number': 30, 'Country': 'Turkey', 'City': 'Istanbul', 'Street': '221sk'}

Upvotes: 1

Related Questions