0% found this document useful (0 votes)
10 views

Sets&Dict Class Code

The document discusses Python sets and dictionaries. It provides examples of creating sets and dictionaries with different data types, performing set operations like union and intersection, and accessing and modifying values in dictionaries. It also demonstrates iterating through keys, values and key-value pairs of dictionaries.

Uploaded by

Lakshmi M
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Sets&Dict Class Code

The document discusses Python sets and dictionaries. It provides examples of creating sets and dictionaries with different data types, performing set operations like union and intersection, and accessing and modifying values in dictionaries. It also demonstrates iterating through keys, values and key-value pairs of dictionaries.

Uploaded by

Lakshmi M
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Set

creation, set constructor


no duplicates, no index
diff datatypes, same value
can access by index, can check presence
loop
add, update, union, |
intersection, &, intersection_update
difference, -, difference_update
symmetric_difference, ^, symmetric_difference_update
< - proper subset <= improper
remove, discard, pop, del, clear

Dictionaries
create, unordered/ordered, immutable:mutable, nodup:dup
a[key] - value vs a.get(key) - diff
retrieve key, values and items
check key
loop - thru keys, values

In [15]: a = {1,2,3}
b = set((4,5,6))
d = [1,2,33]
c = set(d)
print(a,b,c)

{1, 2, 3} {4, 5, 6} {1, 2, 33}

In [16]: a = {'a','b','c',False,3,1}
print(a)

{False, 1, 3, 'b', 'a', 'c'}

In [17]: a = {1,2,3,4,4,4}
print(a)

{1, 2, 3, 4}

In [18]: a = {1,2,3,3,3,4,5,5}
print(len(a))

In [19]: a = {1,2,3,3.0,'3'}
print(len(a))

4
In [20]: a = {1,2,2.0,2+0j,'2',True,False,0}
print(len(a))
print(a)

4
{'2', 1, 2, False}

In [21]: a = {False, 1, 2, '2'}


a[0]

-------------------------------------------------------------------------
--
TypeError Traceback (most recent call las
t)
Cell In[21], line 2
1 a = {False, 1, 2, '2'}
----> 2 a[0]

TypeError: 'set' object is not subscriptable

In [22]: a = {False, 1, 2, '2'}


'2' in a

True
Out[22]:

In [23]: a = {1,2,'a',3,'b'}
for i in a:
print(i)

1
2
3
a
b

In [24]: a = {1,2,3}
a.add(4)
print(a)
b = {7,5,6}
a.update(b)
print(a)

{1, 2, 3, 4}
{1, 2, 3, 4, 5, 6, 7}

In [25]: a = {1,2,3}
b = [7,5,6]
d = (8,9,10)
c = a.union(b,d)
print(a,b,d,c)

{1, 2, 3} [7, 5, 6] (8, 9, 10) {1, 2, 3, 5, 6, 7, 8, 9, 10}

In [26]: a = {1,2,3}
b = [7,5,6]
d = (8,9,10)
c = a | b | d
print(a,b,d,c)
-------------------------------------------------------------------------
--
TypeError Traceback (most recent call las
t)
Cell In[26], line 4
2 b = [7,5,6]
3 d = (8,9,10)
----> 4 c = a | b | d
5 print(a,b,d,c)

TypeError: unsupported operand type(s) for |: 'set' and 'list'

In [27]: a = {1,2,3}
b = {7,5,6}
d = {8,9,10}
c = a | b | d
print(a,b,d,c)

{1, 2, 3} {5, 6, 7} {8, 9, 10} {1, 2, 3, 5, 6, 7, 8, 9, 10}

In [28]: a = {1,2,3}
a.pop()
print(a)

{2, 3}

In [29]: a = {1,2,3}
a.remove(3)
print(a)

{1, 2}

In [30]: a = {1,2,3}
a.clear()
print(a)

set()

In [31]: a = {1,4,3}
a.remove(2)
print(a)

-------------------------------------------------------------------------
--
KeyError Traceback (most recent call las
t)
Cell In[31], line 2
1 a = {1,4,3}
----> 2 a.remove(2)
3 print(a)

KeyError: 2

In [32]: a = {1,4,3,2}
a.discard(2)
print(a)
a = {1,4,3}
a.discard(2)
print(a)

{1, 3, 4}
{1, 3, 4}
In [33]: a = {1,2,3,4}
b = [3,4,5,6]
c = a.intersection(b)
print(c)

{3, 4}

In [34]: a = {1,2,3,4}
b = {3,4,5,6}
c = a & b
print(c)

{3, 4}

In [35]: a = {1,2,3,4}
b = {3,4,5,6}
c = a.difference(b)
d = b - a
print(c,d)

{1, 2} {5, 6}

In [36]: a = {True,1,1}
a

{True}
Out[36]:

In [37]: a = {1,2,3,'4','4',5,4}
print(a)

{1, 2, 3, 4, 5, '4'}

In [38]: a = {1,2,3}
b = [5,6,7]
c = (8,9,99)
d = a.union(b,c)
print(d)

{1, 2, 3, 99, 5, 6, 7, 8, 9}

In [39]: a = {1,2,3}
b = [5,6,7]
c = (8,9,99)
d = a | b | c
print(d)

-------------------------------------------------------------------------
--
TypeError Traceback (most recent call las
t)
Cell In[39], line 4
2 b = [5,6,7]
3 c = (8,9,99)
----> 4 d = a | b | c
5 print(d)

TypeError: unsupported operand type(s) for |: 'set' and 'list'


In [40]: a = {1,2,3,4}
b = {3,4,5,6}
a.intersection_update(b)
print(a)

{3, 4}

In [41]: a = {1,2,3,4}
b = [3,4,5,6]
c = a.difference(b)
#print(c)
print(a)

{1, 2, 3, 4}

In [42]: a = {1,2,3,4}
b = [3,4,5,6]
a.difference_update(b)
print(a)

{1, 2}

In [43]: a = {1,2,3,4}
b = [3,4,5,6]
c = a.difference(b)
print(c)

{1, 2}

In [44]: a = {1,2,3,4}
b = [3,4,5,6]
c = a- b
print(c)

-------------------------------------------------------------------------
--
TypeError Traceback (most recent call las
t)
Cell In[44], line 3
1 a = {1,2,3,4}
2 b = [3,4,5,6]
----> 3 c = a- b
4 print(c)

TypeError: unsupported operand type(s) for -: 'set' and 'list'

In [45]: a = {1,2,3,4}
b = [3,4,5,6]
c = {3,4,5,6}
d = a.symmetric_difference(b)
print(d)
d = a ^ c
print(d)

{1, 2, 5, 6}
{1, 2, 5, 6}

In [46]: a = {1,2,3,4}
b = [3,4,5,6]
a.symmetric_difference_update(b)
print(a)
{1, 2, 5, 6}

In [ ]:

In [47]: a = {1,2,3,4}
b = {1,2,3,4,5}
a<b

True
Out[47]:

In [48]: a = {1,2,3,4}
b = {1,2,3,4}
a<b

False
Out[48]:

In [49]: a = {1,2,3,4}
b = {1,2,3,4}
a<=b

True
Out[49]:

Dictionaries
create, unordered/ordered, immutable:mutable, nodup:dup
a[key] - value vs a.get(key) - diff
retrieve key, values and items
check key
loop - thru keys, values

Dictionaries
create, unordered/ordered, immutable:mutable, nodup:dup
a[key] - value vs a.get(key) - diff
retrieve key, values and items
check key
loop - thru keys, values

In [50]: a = {'a':1,'b':2,'c':3,'c':4}

In [51]: print(a)

{'a': 1, 'b': 2, 'c': 4}

In [52]: print(a.items())

dict_items([('a', 1), ('b', 2), ('c', 4)])

In [53]: print(a.keys())
dict_keys(['a', 'b', 'c'])

In [54]: print(a.values())

dict_values([1, 2, 4])

In [55]: a = {('a','b'):[1,2,3]}
print(a,type(a))

{('a', 'b'): [1, 2, 3]} <class 'dict'>

In [56]: a = {['a','b']:(1,2,3)}

-------------------------------------------------------------------------
--
TypeError Traceback (most recent call las
t)
Cell In[56], line 1
----> 1 a = {['a','b']:(1,2,3)}

TypeError: unhashable type: 'list'

In [57]: a = {'a':1,'b':2,'c':2,'d':3,'d':4}
print(a)

{'a': 1, 'b': 2, 'c': 2, 'd': 4}

In [58]: a = {'a':1,'b':2,'c':2,'d':3,'d':4}
print(a['d'])
print(a.get('d'))

4
4

In [59]: a = {'a':1,'b':2,'c':2,'d':3,'e':4}
#print(a['f'])
print(a.get('c','Key Not Found'))

In [60]: student_scores = {
"Alice": 85,
"Bob": 90,
"Charlie": 78,
"Diana": 92
}

# Iterating over keys


for student in student_scores:
print(student)

# Or explicitly using .keys()


for student in student_scores.keys():
print(student)
Alice
Bob
Charlie
Diana
Alice
Bob
Charlie
Diana

In [61]: # Iterating over values


for score in student_scores.values():
print(score)

85
90
78
92

In [62]: # Iterating over key-value pairs


for student, score in student_scores.items():
print(f"{student} scored {score}")

Alice scored 85
Bob scored 90
Charlie scored 78
Diana scored 92

In [63]: # Example dictionary


student_scores = {
"Alice": 85,
"Bob": 90,
"Charlie": 78,
"Diana": 92
}

# Providing feedback based on scores


for student, score in student_scores.items():
if score > 90:
feedback = "Excellent"
elif score > 80:
feedback = "Good job"
elif score > 70:
feedback = "Keep improving"
else:
feedback = "Needs improvement"

print(f"Student: {student}, Score: {score}, Feedback: {feedback}")

Student: Alice, Score: 85, Feedback: Good job


Student: Bob, Score: 90, Feedback: Good job
Student: Charlie, Score: 78, Feedback: Keep improving
Student: Diana, Score: 92, Feedback: Excellent
In [64]: # Example nested dictionary
class_scores = {
"Class 1": {"Alice": 85, "Bob": 90},
"Class 2": {"Charlie": 78, "Diana": 92}
}

# Iterating through nested dictionary


for class_name, students in class_scores.items():
print(f"\n{class_name}:")
for student, score in students.items():
print(f" {student} scored {score}")

Class 1:
Alice scored 85
Bob scored 90

Class 2:
Charlie scored 78
Diana scored 92

In [65]: # Calculating the average score


total_score = 0
num_students = 0

for score in student_scores.values():


total_score += score
num_students += 1

average_score = total_score / num_students if num_students > 0 else 0


print(f"Average score: {average_score}")

Average score: 86.25

In [66]: # Example dictionaries


scores1 = {"Alice": 85, "Bob": 90}
scores2 = {"Charlie": 78, "Diana": 92}

# Combining dictionaries
combined_scores = {**scores1, **scores2}

# Iterating over combined dictionary


for student, score in combined_scores.items():
print(f"{student} scored {score}")

Alice scored 85
Bob scored 90
Charlie scored 78
Diana scored 92

In [ ]:

You might also like