Soham Practical File
1. Company details dictionary
Code:
c = {'N': 'Example Co.', 'A': 'www.example.com'}
for k, v in c.items():
print(f"{k}: {v}")
Output:
N: Example Co.
A: www.example.com
2. Student information dictionary
Code:
s = {101: {'r': 'A01', 'n': 'John', 'm': 85}, 102: {'r': 'A02', 'n': 'Jane', 'm': 90}}
a = int(input())
if a in s:
print(f"{a}: {s[a]}")
else:
print("Not found.")
Output:
Enter admission number: 101
101: {'r': 'A01', 'n': 'John', 'm': 85}
3. Sort a dictionary alphabetically
Code:
d = {'J': 85, 'A': 90, 'B': 78}
d = dict(sorted(d.items()))
print(d)
Output:
{'A': 90, 'B': 78, 'J': 85}
4. Get 4th element from the beginning and end from a tuple
Code:
t = (1, 2, 3, 4, 5, 6, 7, 8, 9)
print(t[3], t[-4])
Output:
46
5. Find repeated items in a tuple
Code:
t = (1, 2, 3, 3, 4, 5, 4, 1)
r = [x for x in set(t) if t.count(x) > 1]
print(r)
Output:
[1, 3, 4]
6. Create a dictionary of squares
Code:
d = {i: i*i for i in range(1, 16)}
print(d)
Output:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100, 11: 121, 12: 144, 13: 169, 14: 196, 15: 225}
7. Concatenate dictionaries
Code:
d1 = {1: 10, 2: 20}
d2 = {3: 30, 4: 40}
d3 = {5: 50, 6: 60}
r = {**d1, **d2, **d3}
print(r)
Output:
{1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
8. Check if a key exists in a dictionary
Code:
d = {1: 'a', 2: 'b', 3: 'c'}
k=2
print(k in d)
Output:
True
9. Find max and min values in a dictionary
Code:
d = {1: 10, 2: 20, 3: 5}
print(max(d.values()), min(d.values()))
Output:
20 5
10. Create a dictionary from a string
Code:
s = 'resource'
c = {x: s.count(x) for x in set(s)}
print(c)
Output:
{'e': 2, 'r': 2, 's': 1, 'o': 1, 'u': 1, 'c': 1}
Soham Mukherjee--Submitted to Swati Ma'am