Function for extracting data from list

Hi,
I’m struggling with this problem:
create a function named get_data, that takes two arguments, Data and Key.

  • Data is the list of dictionaries in list_1
  • Key are the data that I need to extract from the list of dictionaries list_1.
    This function should then return a list of these attributes.

Example 1:
Input:
get_data(list_1, “name”)
Output:
[“Jerome",“Ibraheem”,“Tiana”,“Lucas”,"Rickie”]

Example 2:
Input:
get_data(list_1, “weight”)
Output:
[3.38,3.08,0.81,3.33,4.4]

I did the following code, but I get as output only the first line:

#  My Code
`def` `main(list_1):`

`    ` `return` `main`

`list_1 ` `=` `[`

`               ` `{` `'name'` `: ` `'Jerome'` `, ` `'weight'` `: ` `3.38` `, ` `'wingspan'` `: ` `49.96` `, ` `'length'` `: ` `19.75` `},`

`               ` `{` `'name'` `: ` `'Ibraheem'` `, ` `'weight'` `: ` `3.08` `, ` `'wingspan'` `: ` `50.59` `, ` `'length'` `: ` `20.6` `},`

`               ` `{` `'name'` `: ` `'Tiana'` `, ` `'weight'` `: ` `0.81` `, ` `'wingspan'` `: ` `47.86` `, ` `'length'` `: ` `17.94` `},`

`               ` `{` `'name'` `: ` `'Lucas'` `, ` `'weight'` `: ` `3.33` `, ` `'wingspan'` `: ` `48.27` `, ` `'length'` `: ` `18.77` `},`

`               ` `{` `'name'` `: ` `'Rickie'` `, ` `'weight'` `: ` `4.4` `, ` `'wingspan'` `: ` `51.0` `, ` `'length'` `: ` `20.34` `}`

`                ` `]`

`def` `get_data(data,key):`

`    ` `for` `key ` `in` `data:`

`        ` `return` `key`

`data ` `=` `list_1`

`key ` `=` `[]`

`output ` `=` `get_data(data,key)`

`print` `(output)`

What do I assign to “key” to get the correct output?

List contain dictionaries (as items in list) and these dictionaries have keys. So you need to iterate over list items (dictionaries) and get value of specific key:

for record in data:                # iterate over dictionaries in list
    print(record['my_magic_key'])  # do something with value on specific key
1 Like