Expt 3
Expt 3
Roll no: 55
Subject: Software Proficiency Program -I
Div: B
Year- TY CSE
Experiment no 3
Title : To implement Sets and dictionaries in python
Sets in Python
A Python set is the collection of the unordered items. Each element in the set
must be unique, immutable, and the sets remove the duplicate elements. Sets
are mutable which means we can modify it after its creation.
Unlike other collections in Python, there is no index attached to the elements of
the set, i.e., we cannot directly access any element of the set by the index.
However, we can print them all together, or we can get the list of elements by
looping through the set.
Creating a set
The set can be created by enclosing the comma-separated immutable
items with the curly braces {}. Python also provides the set() method,
which can be used to create the set by the passed sequence.
", "Sunday"}
2. print(Days)
3. print(type(Days))
5. for i in Days:
6. print(i)
day", "Sunday"])
2. print(Days)
3. print(type(Days))
5. for i in Days:
6. print(i)
It can contain any type of element such as integer, float, tuple etc. But mutable
elements (list, dictionary, set) can't be a member of set.
3. print(months)
5. Months.add("July");
6. Months.add ("August");
8. print(Months)
11. print(i)
5. Months.update(["July","August","September","October"]);
7. print(Months);
3. print(months)
5. months.discard("January");
6. months.discard("May");
8. print(months)
11. print(i)
Dictionaries in Python
Dictionaries are a useful data structure for storing data in Python because
they are capable of imitating real-world data arrangements where a
certain value exists for a given key.
The data is stored as key-value pairs using a Python dictionary.
A dictionary is, in other words, a group of key-value pairs, where the values can
be any Python object. The keys, in contrast, are immutable Python objects, such
as strings, tuples, or numbers. Dictionary entries are ordered as of Python
version 3.7. In Python 3.6 and before, dictionaries are generally unordered.
In the above dictionary Dict, The keys Name and Age are the strings which
comes under the category of an immutable object.
Code
2. print(type(Employee))
Example - 1:
Code
2. Dict = {}
4. print(Dict)
5.
7. Dict[0] = 'Peter'
8. Dict[2] = 'Joseph'
9. Dict[3] = 'Ricky'
11. print(Dict)
12.
18. print(Dict)
19.
23. print(Dict)