Home > Back-end >  how to write a function in python that accepts a list of dictionaries and returns a new list of stri
how to write a function in python that accepts a list of dictionaries and returns a new list of stri

Time:07-23

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

CodePudding user response:

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)

CodePudding user response:

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']
  • Related