簡體   English   中英

如果字典列表中的字典中存在另一個值,如何返回一個值?

[英]How to return a value if another value exists in a dict in a list of dicts?

如何檢查group_list中的字典中group_list存在特定的"type"值? 如果是這樣,我想返回該 dict 的"app"值。

group_list = [
    {
        'type': "app_group1",
        'app': ['vs code', 'notepad', 'google']
    },
    {
        'type': 'app_group2',
        'app': ['slack', 'Discord', 'zoom', 'vs code']
    },
    {
        'type': 'app_group3',
        'app': ['calculater', 'google']
    }]

您可以迭代每個dict以驗證type並返回app就是那個

def get_app(groups, app_type):
    for group in groups:
        if group['type'] == app_type:
            return group['app']
    return None



group_list = [{'type': "app_group1", 'app': ['vs code', 'notepad', 'google', ]},
              {'type': 'app_group2', 'app': ['slack', ' Discord', 'zoom', 'vs code', ]},
              {'type': 'app_group3', 'app': ['calculater', 'google']}]

print(get_app(group_list, 'app_group1'))  # ['vs code', 'notepad', 'google']
print(get_app(group_list, 'app_group5'))  # None

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM