-3

I'm attempting to return out a function but can't find an adequate solution

def importer():
    with open('books.txt','r') as f:
        for line in f:
            books = line.strip().split(',')
            print(books)


    with open('ratings.txt','r') as f:
        for line in f:
            ratings = line.strip().split(' ')
            print(ratings)

     return ratings,books

 importer()

 print(books,ratings)

Using this method the dictionaries are empty again when I get outside my function. To get one out I'd set the function up like

books = importer()

but unsure how to do it for multiple dictionaries

Dharman
  • 21,838
  • 18
  • 57
  • 107
Glasgow
  • 84
  • 7
  • 6
    Possible duplicate of [How do you return multiple values in Python?](https://stackoverflow.com/questions/354883/how-do-you-return-multiple-values-in-python) – ForceBru Mar 11 '18 at 16:46

1 Answers1

2
 ratings, books = importer()

Should be the line of code you're missing, right above your print statement.

Python automatically maps out returning variables. This is loosely called value unpacking. For example this code would map out 1, 2, 3 to x, y, z:

x, y, z = [1,2,3]

You need to have the exact amount of variables as is supplied. Doing x,y = [1,2,3] will return an error, just as x,y,z,a = [1,2,3]

There is a way to bypass this, by using *

x,*y,z = [1,2,3,4,5]

x = 1

y = [2, 3, 4]

z = 5

This property of python, unpacking values, goes much deeper than just lists. Almost anything can be unpacked - tuples, lists, dictionaries, standalone values, ect.

Farstride
  • 145
  • 11