0
0

指定キーのデータがDBから取得したデータに存在するか確認する方法【Python】

Posted at

説明

  1. db_data の各レコードから idcode をキーとしてセットを作成します(db_keys)。
  2. chk_data 内の各データについて、db_keys に同じ idcode のペアが存在するか確認します。
  3. 存在しないものは ng_data リストに追加され、最終的に結果を出力します。
# 処理データ
chk_data = [
    { 'id': 1, 'code': 'A10', 'pos': 52 },
    { 'id': 3, 'code': 'A30', 'pos': 52 },
    { 'id': 4, 'code': 'A40', 'pos': 52 },
    { 'id': 5, 'code': 'A50', 'pos': 52 },
]

# DBデータ
db_data = [
    { 'id': 1, 'code': 'A10', 'pos': 51, 'sort': 101 },
    { 'id': 2, 'code': 'A20', 'pos': 52, 'sort': 102 },
    { 'id': 3, 'code': 'A30', 'pos': 53, 'sort': 103 },
]

# DBデータを (id, code) のセットに変換
db_keys = {(data['id'], data['code']) for data in db_data}

# chk_data の (id, code) をリスト化
chk_keys = [(data['id'], data['code']) for data in chk_data]

# chk_keys に含まれる (id, code) が db_keys に存在しないものをリストに追加
ng_data = [key for key in chk_keys if key not in db_keys]

# 結果を出力
if ng_data:
    print("存在しないデータ:", ng_data)
else:
    print("全てのデータが存在します")

# 存在しないデータ: [(4, 'A40'), (5, 'A50')]
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