0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

データリストからバインド変数と条件文字列の生成方法【Python】

Posted at

説明

  1. データ加工
    • データリストからバインド変数と条件文字列を生成
data_list = [
    {'id': 1, 'code': 'A', 'name': 'apple'},
    {'id': 1, 'code': 'B', 'name': 'banana'},
    {'id': 2, 'code': 'A', 'name': 'cherry'},
    {'id': 2, 'code': 'B', 'name': 'doughnut'}
]

bind_values = {}
conditions = []
for i, item in enumerate(data_list, start=1):
    bind_values[f'id_{i}'] = item['id']
    bind_values[f'code_{i}'] = item['code']
    conditions.append(f'(id = :id_{i} AND code = :code_{i})')
conditions = ' OR '.join(conditions)

print(bind_values)
# {'id_1': 1, 'code_1': 'A', 'id_2': 1, 'code_2': 'B', 'id_3': 2, 'code_3': 'A', 'id_4': 2, 'code_4': 'B'}

print(conditions)
# (id = :id_1 AND code = :code_1) OR (id = :id_2 AND code = :code_2) OR (id = :id_3 AND code = :code_3) OR (id = :id_4 AND code = :code_4)
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?