0

I'm working with collection's namedtuple to return a list of tuple from within a function as such:

def getItems(things_list) -> list:
    for i, j in enumerate(things_list):
        [*things_id] = things_list[i].id
        [*things_title] = things_list[i].title
        things_structure = namedtuple('things', ['id', 'title'])
        [*things_list] = [
            things_structure(things_id, things_title)
        ]
    return things_list

if I run

callGetItems = getItems(list_of_things)  # assume list_of_things is a dictionary
print(callGetItems)

it will only print the first index of the return value, as you can see I'm actually expecting the whole dictionary to be printed with their respective id and title.(assume there is at least 3 different Key-value pairs in the dictionary)

P.s. If I print within the function, it prints all the elements stored in the [*things_list] variable as expected but the same cannot be said for iterating over the return value i.e., outside of the function. please help.

to deobfuscate things assume this is the dictionary list_of_things:

list_of_things = [
    {"id" : 1,
     "title" : "waterbottle",
     "description" : "a liquid container"},
    {"id": 2,
     "title": "lunchbox",
     "description": "a food container"}
]
# etc... 
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • your list of things is a dictionary of lists. I think you meant to flip your { and [ symbols. and create a list of dictionaries. Correct?? – Brad Day Apr 27 '21 at 16:37
  • @BradDay Yes like that. apologies I might have mixed up some things in the explanation. – sailormoonbs Apr 27 '21 at 16:42

1 Answers1

0

Is this what you were going for? Creating a list of named tuples from the original list of dicts?

from collections import namedtuple
list_of_things = [
    {"id": 1, "title": "waterbottle", "description": "a liquid container"},
    {"id": 2, "title": "lunchbox", "description": "a food container"},
]
def getItems(things_list) -> list:
    things_structure = namedtuple("things", ["id", "title"])
    return [things_structure(k["id"], k["title"]) for k in things_list]
new_things = getItems(list_of_things)
print(new_things)
Brad Day
  • 400
  • 2
  • 9
  • thanks this works! but i just realised i can use python's append() method to append the tuple to a variable list and then return that at the end. but if i'm mistaken could you please explain how that return line works on your example? k["id"], k["title"] - is k indexing over each key in the dictionary and doing a mix and match with the ["id"] and so on? – sailormoonbs Apr 27 '21 at 20:18
  • Yah we are using list comprehension. We are iterating over the elements of `thing_list` which is a list of dicts and then each `k` is a dict and we are using the keys `id` & `title` to index `k` and place into the named tuple. I probably should have used a different variable name then `k` as that could be confusing making it seem as though it meant keys – Brad Day Apr 28 '21 at 14:47