0% found this document useful (0 votes)
15 views2 pages

Practical - 3 - Jupyter Notebook

Uploaded by

ganeta2963
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)
15 views2 pages

Practical - 3 - Jupyter Notebook

Uploaded by

ganeta2963
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/ 2

10/9/24, 12:39 PM Practical_3 - Jupyter Notebook

Practical - 3

A Write a Python script to check if a given key already exists in a


dictionary.

my_dict = {1: 'a', 2: 'b', 3: 'c'}

In [9]: my_dict = { 1:'a' , 2:'b' , 3:'c'}


key_to_check = 2
if key_to_check in my_dict:
print(f"key {key_to_check} exists in the dictionary")
else:
print(f"key {key_to_check} does not exist in the dictionary")

key 2 exists in the dictionary

Write a Python script to merge two Python dictionaries.

dict_1 = {1: 'a', 2: 'b’}

dict_2 = {2: 'c', 4: 'd'}

In [11]: dict_1 = {1:'a' , 2: 'b'}


dict_2 = {3:'c' , 4: 'd'}

merge_dict = {**dict_1 , **dict_2}
print(merge_dict)

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

C) Add member(s) in a set

In [12]: my_set = {1, 2, 3}


members_to_add = {4, 5}

my_set.update(members_to_add)
print(my_set)

{1, 2, 3, 4, 5}

localhost:8889/notebooks/Practical_3.ipynb 1/2
10/9/24, 12:39 PM Practical_3 - Jupyter Notebook

D) Remove items 10, 20, 30 from a set at once

In [13]: my_set = {10, 20, 30, 40, 50}



items_to_remove = {10, 20, 30}
my_set.difference_update(items_to_remove)

print(my_set)

{50, 40}

E) Sort a dictionary by value (ascending and descending)

In [14]: my_dict = {
"Blue": 3,
"Orange": 5,
"Yellow": 6,
"Red": 7,
"Violet": 1,
"Green": 4,
"Indigo": 2
}

sorted_asc = dict(sorted(my_dict.items(), key=lambda item: item[1]))
print("Sorted in ascending order:", sorted_asc)

sorted_desc = dict(sorted(my_dict.items(), key=lambda item: item[1], reverse
print("Sorted in descending order:", sorted_desc)

Sorted in ascending order: {'Violet': 1, 'Indigo': 2, 'Blue': 3, 'Green':


4, 'Orange': 5, 'Yellow': 6, 'Red': 7}
Sorted in descending order: {'Red': 7, 'Yellow': 6, 'Orange': 5, 'Green':
4, 'Blue': 3, 'Indigo': 2, 'Violet': 1}

In [ ]: ​

localhost:8889/notebooks/Practical_3.ipynb 2/2

You might also like