Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Collections (2016, retired 2019) Dictionaries Packing and Unpacking Dictionaries

aditya yadav
aditya yadav
1,505 Points

how can we pass dictionary (as argument) in a function

how can we pass dictionary (as argument) in a function

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,457 Points

Any object can be passed as an argument to a function, including other functions.

pass_dict.py
# give a function that changes dict keys to uppercase
def func(obj1):
    for key in obj1:
        obj1[key.upper()] = obj1.pop(key)

# a function that accepts a dict and a function and applies the function to the dict
def dict_swizzle(dct, fct):
    # apply fct to dct
    fct(dct)

# A basic dict
dct1 = {"these": 1, "are": 2, "keys":3}

# Call the function with a dict and a function
dict_swizzle(dct1, func)

# print the results
# Note that changes to the dict are visible outside the function
print(dct1)

Running this in a shell produces the results:

> python pass_dict.py
{'KEYS': 3, 'THESE': 1, 'ARE': 2}

Wow Chris Freeman thanks for this example!

Can you elaborate on why the pop is necessary in line 4? I would have (mistakenly) thought obj1[key.upper()] would have worked. Then further, I thought why doesn't popping the key destroy the key/value pair before the assignment? Or does pop(key) pop the entire key/value pair? Just not sure how this works.

Chris Freeman
Chris Freeman
Treehouse Moderator 68,457 Points

Can you elaborate on why the pop is necessary in line 4? Certainly, without the pop the old key/value pair would remain leading to two similar keys, but one uppercased, thus doubling the size of the dict. Of course, if the key was already uppercase then nothing would change.

I would have (mistakenly) thought obj1[key.upper()] would have worked. Then further, I thought why doesn't popping the key destroy the key/value pair before the assignment? The pop removes the key/value pair from the dict but it's held as the return value so the assignment can happen. In the same fashion why this works:

# exchange values
a, b = b, a

Or does pop(key) pop the entire key/value pair? correct.

Just not sure how this works. now you do!

Thanks!