ShoeShineBoy
ShoeShineBoy

Reputation: 82

How to assign dictionary to another dictionary?

So I want to create a function that accepts values for dictionary, creates new dictionary and returns it. Then I want to assign that value in other places of code. But I get Type Error dict object is not callable. How can I do this?

def shoe(brand, model):
    shoe = {}
    shoe['brand'] = brand
    shoe['model'] = model
    return shoe


 shoes_list = []
 shoe = {}

 shoe = shoe('Some Brand', 'Some model')

 print(shoe)

Upvotes: 1

Views: 695

Answers (2)

Code-Apprentice
Code-Apprentice

Reputation: 83587

def shoe(brand, model):

Here you create a function named shoe.

    shoe = {}

Now you create a variable named shoe and assign a dictionary to it. This isn't a problem yet since this variable is local inside of the function. However, it can be very confusing to reuse the same name in this way. I suggest changing this variable's name.

    shoe['brand'] = brand
    shoe['model'] = model
    return shoe


 shoes_list = []
 shoe = {}

Now you are reassigning the name shoe to refer to an empty dictionary instead of the function that it used to refer to. This will cause later calls to the function with shoe() to fail.


 shoe = shoe('Some Brand', 'Some model')

And then you try to assign the return value of the function to the name shoe(). I assume this is where the function call fails. Note that if you fix this, you don't need shoe = {} at all.


 print(shoe)

You are using the same name for two different things: once for the name of your function and once for the name of your dictionary. Use two different names to fix the problem. In general, function names should be verbs. So you can do get_shoe() or create_shoe() for the function name. Then using the noun shoe for the dictionary will be fine.

Upvotes: 1

interfect
interfect

Reputation: 2877

You need your function and your original dict to have different names:

def make_shoe(brand, model):
    shoe = {}
    shoe['brand'] = brand
    shoe['model'] = model
    return shoe


 shoes_list = []
 shoe = {}

 shoe = make_shoe('Some Brand', 'Some model')

 print(shoe)

Note also that you are not filling in the dict you stored in shoe; you are making a new dict to replace it. If you want to fill it in, you would do something like this:

def fill_in(brand, model, dest):
    dest['brand'] = brand
    dest['model'] = model


 shoes_list = []
 shoe = {}

 fill_in('Some Brand', 'Some model', shoe)

 print(shoe)

Upvotes: 1

Related Questions