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件取得
def find_match_data(key_info, data_list):
    for data in data_list:
        if all(data.get(k) == v for k, v in key_info.items()):
            return data
    return None

# 取得条件
key_info = {
    'id': 1,
    'code': 'A'
}

# データリスト
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'}
]

match_data = find_match_data(key_info, data_list)

print(match_data)
# {'id': 1, 'code': 'A', 'name': 'apple'}
# 複数件取得
def select_match_data(key_info, data_list):
    match_list = []
    for data in data_list:
        if all(data.get(k) == v for k, v in key_info.items()):
            match_list.append(data)
    return match_list

# 取得条件
key_info = {
    'id': 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'}
]

match_data = select_match_data(key_info, data_list)

print(match_data)  

# [{'id': 1, 'code': 'A', 'name': 'apple'}, {'id': 1, 'code': 'B', 'name': 'banana'}]
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?