2

I am new to python and trying to write a function that accepts a list of dictionaries and returns a new list of strings with the first and last name keys in each dictionary concatenated.

names = [{'first': 'John', 'last': 'Smith'}, {'first': 'Jessie', 'last': 'Snow'}]


 def name_function(lst):     
     for name in lst:       
         return f"{name['first']} {name['last']}" 

 names_function(names)
 'John Smith'

I wrote a for loop that iterates thru the list of dictionaries and returns an f-string that concatenates first and last name keys in each dictionary, however, the loop fails to iterate beyond the first key and I am hoping some one can point me to the issue.

Jane P
  • 99
  • 2
  • 6

2 Answers2

2

While you have a loop, you also have a return inside the loop. On the first iteration of the list this return will be hit and execution of the function will stop there, returning only value on that line — which is a string — rather than the list intended.

You either need to add a list to the function to use as an accumulator before returning —

def names_function(lst):  
    names = []      
    for name in lst:       
        names.append(f"{name['first']} {name['last']}")
    return names   

Or to use a list comprehension

def names_function(lst):  
    return [f"{name['first']} {name['last']}" for name in lst]

names_function(names)

Both will output

['John Smith', 'Jessie Snow']

You could also replace the return with a yield to turn this into a generator. To get all the values you would need to iterate the generator (or call list on it)

def names_function(lst):     
    for name in lst:       
        yield f"{name['first']} {name['last']}" 

list(names_function(names))

Which gives the same result

['John Smith', 'Jessie Snow']
mfitzp
  • 15,275
  • 7
  • 50
  • 70
0

if you wantto get all names:

def names_function(lst):
    ret=""
    for name in lst:
        ret += f"{name['first']} {name['last']}\n"
    return ret

or

def names_function(lst):
    return [f"{name['first']} {name['last']}" for name in lst]

if you want to create a generator object:

def names_function(lst):
    return (f"{name['first']} {name['last']}" for name in lst)