213k views
4 votes
Given the list of customer segments below please create a new list of the names of the segments only using(a) a for loop(b) a list comprehension(c) a map().List would look something like ['Wallstreet','Gambler','Parents'] but of course using each tool as listed:segments = [{'name': 'Wallstreet', 'average_spend': 82.01}, {'name': 'Gambler', 'average_spend': 107.00}, {'name': 'Parents', 'average_spend': 10.52}]

User Alica
by
5.2k points

1 Answer

3 votes

Answer:

new_segment = [ ]

for segment in segments:

new_segment.append({'name': segment, 'average_spend': money})

print( new_segment)

Using list comprehension:

new_segment =[{'name': segment, 'average_spend': money} for segment in segments]

Using map():

def listing(a):

contain = {'name': segment, 'average_spend': money}

return contain

new_segment = [ ]

new_segment.append(map( listing, segment))

print(list(new_segment)

Step-by-step explanation:

The python codes above create a list of dictionaries in all instances using for loop, for loop in list comprehension and the map function which collect two arguments .

User Marek Vitek
by
5.0k points