-1
def build_profile(first, last, **user_info):
"""Build a dictionary containing everything we know about a user."""
user_info['first_name'] = first
user_info['last_name'] = last
return user_info


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

Output:

{'location': 'princeton', 'field': 'physics', 'first_name': 'albert', 'last_name': 'einstein'}

I dont understand why the key and value first_name and last_name was placed at the last? aren't they supposed to be placed before location and field? because of positional arguments??

please help.

rv.kvetch
  • 9,940
  • 3
  • 24
  • 53
kkls_00
  • 11
  • 1

1 Answers1

1

In case you'd want the positional arguments passed in to the function to come before the **kwargs passed in, you could use the dict(..., **kwargs) approach to build a new dict object:

def build_profile(first, last, **addl_info):
    """Build a dictionary containing everything we know about a user."""
    user_info = {'first_name': first, 'last_name': last, **addl_info}
    return user_info


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

Out:

{'first_name': 'albert', 'last_name': 'einstein', 'location': 'princeton', 'field': 'physics'}
rv.kvetch
  • 9,940
  • 3
  • 24
  • 53
  • im still trying to understand, since (first and last ) were placed first inside the parameter, and we return the user_info, and then when you build the profile, we call albert and einstein first, why is the ouput showing key value pairs at the last? – kkls_00 Aug 25 '22 at 16:19
  • If you mean why are the `**kwarg` parts at the end (location and field), I believe thats due to the order we're passing them in to the constructor. That is, we're passing `dict(first, last, **kwargs)` rather than trying to update the `kwargs` object, which already has the keys location and field in our case. – rv.kvetch Aug 25 '22 at 17:10