Home > Blockchain >  How to return a value if another value exists in a dict in a list of dicts?
How to return a value if another value exists in a dict in a list of dicts?

Time:11-07

How can I check if a specific "type" value exists in a dict in group_list? If it does, I want to return that dict's "app" value.

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']
    }]

CodePudding user response:

You may iterate on each dict to verify the type and return the app is that's the one

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
  • Related