Home > Enterprise >  Python return list of values associated with specific key in list of dictionaries [closed]
Python return list of values associated with specific key in list of dictionaries [closed]

Time:09-22

I have a list of dicts :

my_dict = [{'Serial': 'AAAAAA', 'Slave_ID': 2},{'Serial': 'BBBBBB', 'Slave_ID': 3}, {'Serial': 'AAAAAA', 'Slave_ID': 5}]

Could someone suggest me a way to extract the list of slave_ID's for a particular Serial number? For example(pseudo code):

Extract_slave_id('AAAAAA'):
   #returns a list of slave id's associated with serial 'AAAAAA'
   list = [5,2]
   return list

Thanks in advance.

CodePudding user response:

my_id = 'AAAAAA'
extracted_ids = [element['Slave_ID'] for element in my_dict if element['Serial'] == my_id]

CodePudding user response:

data = [{'Serial': 'AAAAAA', 'Slave_ID': 2}, {'Serial': 'BBBBBB', 'Slave_ID': 3},
        {'Serial': 'AAAAAA', 'Slave_ID': 5}]


def extract_slave_ids(slave_id, data):
    return [item['Slave_ID'] for item in data if item['Serial'] == slave_id]


print(extract_slave_ids('AAAAAA', data))

Outputs:

[2, 5]
  • Related