2

Sorry, I am new to Python and stuck on this function.

item_pencil = {
    "id": "pencil",

    "name": "a HB Pencil",

    "description":
    "Normal pencil"
}

item_pen = {
    "id": "pen",

    "name": "a Ballpoint Pen",

    "description":
    "Standard ballpoint pen"
}

I have coded this function but it returns everything about the items

def list_of_items(items):
    n = ",".join(map(str, items))
    #n = ",".join([str(name) for name in items])
    return n

print(list_of_items([item_pen, item_pencil]))

The output I get

{'id': 'pen', 'name': 'a Ballpoint Pen', 'description': 'Standard ballpoint pen.'}, 
{'id': 'pencil', 'name': 'a HB Pencil', 'description': 'Normal Pencil'}

But the output I want is this

'a Ballpoint Pen, a HB Pencil'

I'm sorry if I am missing something obvious. Thanks in advance

Jonathan
  • 39
  • 3

1 Answers1

1

You are almost close. You need to iterate through list and get the value for the 'name' key:

def list_of_items(items):
    n = ", ".join([item['name'] for item in items])
    return n

You can use both list comprehension or generator :

', '.join([item['name']) for item in items])  # list comprehension
', '.join(item['name'] for item in items)     # generator expression

But list comprehension is both faster and more memory efficient [source].

Austin
  • 25,759
  • 4
  • 25
  • 48
  • `str.join()` takes any iterable so you can use a generator expression instead of a list expression, ie `n = ", ".join(item["name"] for item in items)` - this avoids building a list object for nothing. – bruno desthuilliers Oct 18 '18 at 10:17
  • @brunodesthuilliers `str.join()` is more efficient with a list comprehension than with a generator. – Austin Oct 18 '18 at 10:18