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.

3
  • a return immediately exits a function and returns the value. you need to store the strings in a list, and return the list at the end. (or opt for other alternatives, yield for example) Commented Feb 17, 2019 at 15:20
  • Because you return in the first iteration. Commented Feb 17, 2019 at 15:21
  • 2
    Just return [f"{name['first']} {name['last']}" for name in lst] without loop. Commented Feb 17, 2019 at 15:23

2 Answers 2

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']
Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.