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 trialaditya yadav
1,505 Pointshow can we pass dictionary (as argument) in a function
how can we pass dictionary (as argument) in a function
1 Answer
Chris Freeman
Treehouse Moderator 68,441 PointsAny object can be passed as an argument to a function, including other functions.
# 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}
Keith Ostertag
16,619 PointsKeith Ostertag
16,619 PointsWow 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
Treehouse Moderator 68,441 PointsChris Freeman
Treehouse Moderator 68,441 PointsCan 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:Or does pop(key) pop the entire key/value pair? correct.
Just not sure how this works. now you do!
Keith Ostertag
16,619 PointsKeith Ostertag
16,619 PointsThanks!
aditya yadav
1,505 Pointsaditya yadav
1,505 PointsThanks