Python Forum

Full Version: function for extracting data from lists
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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:

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?
You need to iterate through the list, check if key in in the dictionary, and if so display results

pseudo code:
for each item in list_1
    for each key in keys
        display key and value (no newline)
    display newline
to display without newline, use like: print(f"{key:8} {adict[key]:10} ", end="")
the :8 and :10 are qualifiers that indicate width of field.
OK thanks, then I did the following 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):
    y=[]
    for x in data:
        return y=x[key]
data = list_1
get_data(list_1,'length')
output = get_data(data,key)
print(output, end=" ")
I'm getting a syntax error in "return y=x[key]", why is that?
Why are you trying to assign to a variable in a return statement? return is for returning a value to the caller of the function.
OK thanks, then my understanding from your comment is the below, but didn't work as well:

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):
    y = []
    for x in data:
      y=x[key]
      return y
data = list_1
get_data(list_1,'length')
output = get_data(data,key)
print(output, end=" ")
Try:
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, keys):
    for adict in list_1:
        for key in keys:
            if key in adict:
                print(f"{key:8} {adict[key]:10} ", end="")
        print()

def testit():
    get_data(["Jerome","Ibraheem","Tiana","Lucas","Rickie"], ['name', 'weight'])

testit()
gives you:
Output:
name Jerome weight 3.38 name Ibraheem weight 3.08 name Tiana weight 0.81 name Lucas weight 3.33 name Rickie weight 4.4
(Sorry Larz, we were almost at the same time answering.)

Very well, you are making progress. But you should be more precise than saying: " but didn't work as well". You get the following message, right?
Error:
Traceback (most recent call last): File "/home/ibreeden/PycharmProjects/Forum/venv/impos01.py", line 23, in <module> output = get_data(data, key) NameError: name 'key' is not defined
It is because you write:
get_data(list_1,'length')
output = get_data(data,key)
Replace that with:
output = get_data(list_1, 'length')
Output:
19.75
Now this is still not what you want, because this is only the first occurence.
In the function get_data() you have a return in the for-loop. That is wrong. You must return after the loop has finished. So unindent the return statement.
Output:
20.34
Still not what you want, now it shows only the last occurrence. Have a look at the list "y = []". Do you know how to append() values to a list?
Thanks for the help, I'm nearly there.... hopefully: now I have the code below that works and gives the last value of the list as you said. Then I tried to use "append" in order to have all the values (or names) and from my understanding I should append the output of each iteration inside the loop, but still get error "'float' object has no attribute 'append'", as per the below code. So how can I append each output from the for loop to the previous one in order to get the desired results in one line, e.g. [19.75, 20.06, 17.94, 18.77, 20.34]?

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):
    y = []
    for x in data:
      y=x[key]
      y.append(x)
    return y
data = list_1
get_data(list_1,'length')
output = get_data(list_1, 'length')
print(output, end=" ")
Nono, this is what you do:
y = []       # create empty list with name "y"
...
y=x[key]     # y = 19.75; Now y is a floating point number
y.append(x)  # append something to a float???
append() is a method of list. So you must do:
y = []
...
y.append(x[key])
... and after the for-loop has finished you will have a list with all the data that you want.
Wow... OK now I understand!! Many thanks, I was becoming crazy complicating thing and looping my brain instead of coding, now it finally works as expected (below the correct code). Many thanks again, in particular with the details: they helped me to understand things more linearly.

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):
    y = []
    for x in data:
      y.append(x[key])
    return y
data = list_1
get_data(list_1,'length')
output = get_data(list_1, 'length')
print(output, end=" ")