Pepper
Pepper

Reputation: 65

How to extract specific value from list of list of dictionary?

I'm trying to extract the value of "Alt_name" and need to store it as a list.

Input:

[
 [{'Name': 'Selin', 'Age': '31', 'Active': 'true', 'Items': '4', 'Alt_name': 'selin-hub', 'type': 'Normal', 'Colour':'Blue'}],
 [{'Name': 'Jenny', 'Age': '21', 'Active': 'true', 'Items': '2', 'Alt_name': 'jenny-cean', 'type': 'Normal', 'Colour': 'green'}],
 [{'Name': 'Vuly', 'Age': '20', 'Active': 'true', 'Items': '3', 'Alt_name': 'clary', 'type': 'Normal'}] 
]

Expected Output:

 ['selin-hub','jenny-cean','clary']

How to extract the value of Alt_name from the above input?

Thanks in advance.

Upvotes: 0

Views: 94

Answers (1)

houtanb
houtanb

Reputation: 4100

You have a list of lists, each containing a dictionary. So, just rifle through the lists, choosing the first element (the dictionary), then choosing the 'Alt_name' field.

Setting your list to the variable l, you could find the desired output by using a List Comprehension:

[d[0]['Alt_name'] for d in l]

If you can modify this list, you might consider just making it a list of dictionaries, i.e.:

l = [
    {'Name': 'Selin', 'Age': '31', 'Active': 'true', 'Items': '4', 'Alt_name': 'selin-hub', 'type': 'Normal', 'Colour':'Blue'},
    {'Name': 'Jenny', 'Age': '21', 'Active': 'true', 'Items': '2', 'Alt_name': 'jenny-cean', 'type': 'Normal', 'Colour': 'green'},
    {'Name': 'Vuly', 'Age': '20', 'Active': 'true', 'Items': '3', 'Alt_name': 'clary', 'type': 'Normal'}
]

in which case you could obtain the desired output by writing

[d['Alt_name'] for d in l]

Upvotes: 2

Related Questions