Python, I got a value from the database, so I have a question when I use it.

Asked 2 years ago, Updated 2 years ago, 86 views

I put the value I received in the database into the list as append, and when I write the value of each kernel, I filter the list[] twice in the array as shown in 1, remove the tuple(), and use it after removing the tuple(). I wonder what other people do.

And if you take the records value from the DB and dict it at number 2, it becomes key, value, sqlalchmy at python.py.engine.. I also want to know how it becomes key and value right away from the value.

python.py

records = db.session.execute(db.session.query(table))
# # records = [<sqlalchemy.engine.result.ResultProxy object at 0x7fd035e8d7d0>]


1

season = []
for row in records:
    season.append(row)

# # season = [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

for i in range(len(season)):
    result = season[i]
    # # season[0] = (1, 'Spring')
    result1 = result[0]
    result2 = result[1]
    print(result1)
    print(result2)

Results:
1
Spring
2
Summer
3
Fall
4
Winter

2

aaa=[dict(record) for record in season]
print(aaa)
Results:
[{1 : 'Spring', 2 : 'Summer', 3 : 'Fall', 4 : 'Winter'}]

python append key value

2022-09-21 22:09

1 Answers

I don't think it's a problem that's limited to databases.

Tuple can be unpacked.

result1, result2 = result

The conversion to dict is done internally.

In fact, the Python db module (specification) is supposed to receive only the tuple.

However, mysql driver also provides additional services such as DictCursor.

The reason why processing is possible is because you also receive meta information from the table, so you can know the column name of the table. Because you know the column name {'column name':value} You can convert to a dict such as .

And in the question, you asked about the transformation of tuple -> dict, the first element of tuple is the key, and the second is the value.


2022-09-21 22:09

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.