-2

how to write a function in python that accepts a list of dictionaries and returns a new list of strings

    """
    name = [{"first":"john","last":"doe"},{"first":"jane","last":"doe"}]
    **function should accept name as the argument** 
    extract_name(name):
    
    expected o/p = # ['john Doe','jane Doe']

    """

I have tried these codes

name = [{"first":"john","last":"doe"},{"first":"jane","last":"doe"}]

def extract_names(name):
    for id in name:
        res = id.values()
        print(list(res))
extract_names(name)

"""
output
['john', 'doe']
['jane', 'doe']
"""

But im getting the o/p on two different lines also I wanna know how can map help in this problem

I'mahdi
  • 23,382
  • 5
  • 22
  • 30
Karizkhan
  • 1
  • 2
  • Does this answer your question? [How do I convert a list into a string with spaces in Python?](https://stackoverflow.com/questions/12309976/how-do-i-convert-a-list-into-a-string-with-spaces-in-python) – mkrieger1 Jul 23 '22 at 11:00
  • Also see https://stackoverflow.com/questions/44564414/how-can-i-use-return-to-get-back-multiple-values-from-a-for-loop-can-i-put-th for how to add multiple results to a list instead of just printing them. – mkrieger1 Jul 23 '22 at 11:36

2 Answers2

3

Another solution, using map() and str.format_map:

name = [{"first": "john", "last": "doe"}, {"first": "jane", "last": "doe"}]

out = list(map("{first} {last}".format_map, name))
print(out)

Prints:

['john doe', 'jane doe']

If you want a function:

def fn(names):
    return list(map("{first} {last}".format_map, names))


out = fn(name)
print(out)
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
2

IIUC, you can iterate over dict and use f-string for getting what you want.

# each element is dict:
name = [{"first":"john","last":"doe"},{"first":"jane","last":"doe"}]
# dict : ^^^^^^^^^^^^^^^^^^^^^^^^^^^ , ^^^^^^^^^^^^^^^^^^^^^^^^^^^^

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

res = extract_name(name)
print(res)

['john doe', 'jane doe']

You can use list comprehensions.

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

If you want to do with map.

>>> list(map(lambda x: f"{x['first']} {x['last']}", name))
['john doe', 'jane doe']
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
I'mahdi
  • 23,382
  • 5
  • 22
  • 30