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

Kenneth says that "like dictionaries", we can use the update function. What does he mean by that?

I watched the dictionaries video but i don't remember using any update function on dictionaries. what does Kenneth mean by that? How can we use the update function on a dictionary similar to the one we use on sets? thanks

1 Answer

I think he means that you can use the update() method on sets and dictionaries.

Of course sets will add unique values while dictionaries will update existing keys.

Here's some code to play with and hopefully clear things up a bit:

list1 = [1, 2, 3, 1, 2, 3]
list2 = [5, 6, 7, 5, 6, 7, 'zzz']

set1 = set(list1)
set2 = set(list2)
set3 = set(list1)
set4 = set(list2)

print('Set1 is ---> {}'.format(set1))
print('Set2 is ---> {}'.format(set2))
print('Set3 is ---> {}'.format(set3))
print('Set4 is ---> {}'.format(set4))

set2.update(set1)

print('Updated Set2 is ---> {}'.format(set2))

dict1 = {x: y for x, y in enumerate(set3)}
dict2 = {x: y for x, y in enumerate(set4)}

for k, v in dict1.items():
    print('Before Update Key is {} and value is {}'.format(k, v))

dict1.update(dict2)

for k, v in dict1.items():
    print('After Update Key is {} and value is {}'.format(k, v))

#outputs
Set1 is ---> {1, 2, 3}
Set2 is ---> {'zzz', 5, 6, 7}
Set3 is ---> {1, 2, 3}
Set4 is ---> {'zzz', 5, 6, 7}
Updated Set2 is ---> {1, 2, 3, 5, 6, 7, 'zzz'}
Before Update Key is 0 and value is 1
Before Update Key is 1 and value is 2
Before Update Key is 2 and value is 3
After Update Key is 0 and value is zzz
After Update Key is 1 and value is 5
After Update Key is 2 and value is 6
After Update Key is 3 and value is 7