Daniel Scan
Daniel Scan

Reputation: 11

Dictionary in Function

def build_profile(first, last, **user_info):  

    profile = {}   
    profile['first_name'] = first 
    profile['last_name'] = last

    for key, value in user_info.items():
        profile[key] = value

    return profile

user_profile = build_profile('albert', 'einstein',
location='princeton',field='physics')
print(user_profile)

Hello guys! Just started studying python a week ago from the book "Python Crash Course", I have a little question about this program.

Why in the build_profile they write location='princeton' and not 'location' = 'princeton'

Upvotes: 0

Views: 95

Answers (3)

Richard Stoeffel
Richard Stoeffel

Reputation: 695

you should read up on this question Understanding kwargs in Python to understand what you are doing, but that **user_info is described as keyword argument (and is usually written as **kwargs). When calling that funciton, since it includes a **kwargs input, you can write in any additional fields you might want. Then, this function:
for key, value in user_info.items(): profile[key] = value

Creates those variables in the profile dict

Upvotes: 0

Brandon Barney
Brandon Barney

Reputation: 2392

What is happening is location and field both become part of **kwargs or, in this case **user_info. kwargs stands for keyword arguments and thus Python recognizes that the user can enter a number of keyword parameters, and will happily accept them.

What is happening at a deeper level is a dictionary is passed to build profile that looks something like this:

user_info = {'location':'princeton', 'field':'physics'}

This means that it is possible to pass a dictionary to any **kwargs argument. In the case of supplying keywords instead, Python will, in essence, build the dictionary automatically.

Upvotes: 1

Lost
Lost

Reputation: 1008

Those are not actually a dictionary that you are passing into your function, they are keyword arguments which you can read about in the Python documentation linked.

Keyword arguments have a lot of uses which are too many to enumerate here.

In your function definition ** means (and some additional keyword arguments) which allows the user to provide any keyword arguments they want. Try adding random_key="test" for example

Upvotes: 0

Related Questions