1my_dict = {2:3, 5:6, 8:9}
2
3new_dict = {}
4for k, v in my_dict.items():
5 new_dict[v] = k
1# You can't create a set like this in Python
2my_set = {} # ---- This is a Dictionary/Hashmap
3
4# To create a empty set you have to use the built in method:
5my_set = set() # Correct!
6
7
8set_example = {1,3,2,5,3,6}
9print(set_example)
10
11# OUTPUT
12# {1,3,2,5,6} ---- Sets do not contain duplicates and are unordered
13
1>>> A = {0, 2, 4, 6, 8};
2>>> B = {1, 2, 3, 4, 5};
3
4>>> print("Union :", A | B)
5Union : {0, 1, 2, 3, 4, 5, 6, 8}
6
7>>> print("Intersection :", A & B)
8Intersection : {2, 4}
9
10>>> print("Difference :", A - B)
11Difference : {0, 8, 6}
12
13# elements not present both sets
14>>> print("Symmetric difference :", A ^ B)
15Symmetric difference : {0, 1, 3, 5, 6, 8}
16
1The simplest way to create set is:
21. from list
3code:
4 s = [1,2,3]
5 set = set(s)
6 print(set)
7
82. s,add() method
9code:
10 set.add(1)
11 set.add(2)
12 set.remove(2)
13 print(set) // 1
14
153. Set conatins unique elements
1basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
2print(basket) # show that duplicates have been removed
3# OUTPUT {'orange', 'banana', 'pear', 'apple'}
4print('orange' in basket) # fast membership testing
5# OUTPUT True
6print('crabgrass' in basket)
7# OUTPUT False
8
9# Demonstrate set operations on unique letters from two words
10
11print(a = set('abracadabra'))
12print(b = set('alacazam'))
13print(a) # unique letters in a
14# OUTPUT {'a', 'r', 'b', 'c', 'd'}
15print(a - b) # letters in a but not in b
16# OUTPUT {'r', 'd', 'b'}
17print(a | b) # letters in a or b or both
18# OUTPUT {'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
19print(a & b) # letters in both a and b
20# OUTPUT {'a', 'c'}
21print(a ^ b) # letters in a or b but not both
22# OUTPUT {'r', 'd', 'b', 'm', 'z', 'l'}
1set_of_base10_numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0}
2set_of_base2_numbers = {1, 0}
3
4intersection = set_of_base10_numbers.intersection(set_of_base2_numbers)
5union = set_of_base10_numbers.union(set_of_base2_numbers)
6
7'''
8intersection: {0, 1}:
9 if the number is contained in both sets it becomes part of the intersection
10union: {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}:
11 if the number exists in at lease one of the sets it becomes part of the union
12'''