Dic data type
In Python, dictionaries are unordered collections of unique values stored in (Key-Value) pairs. Use a dictionary data type to store data as a key-value pair.
The disctionary type is represented using a dict class. For example, if you want to store the name and roll number of all students, then you can use the dict type.
In a dictionary, duplicate keys are not allowed, but the value can be duplicated. If we try to insert a value with a duplicated key, the old value will be replaced with the new value.
Dictionary has some characteristics which are listed below:
- A heterogeneous (i.e. str, list, tuple) elements are allowed for both key and value in a dictionary. But an object can be a key in a dictionary if it is hashable.
- The dictionary is mutable which means we can modify its items
- Dictionary is unordered so we can't perform indexing and slicing
We can create a dictionary using the two ways:
- By enclosing key and values in the curly brackets { }
- Using a dict () class.
Example dictionary creation and manipulation
# create a dictionary
dict = {1: "John", 2: "Jenny", 3: "Jess"}
# display dictionary
print(dict) # {1: 'John', 2: 'Jenny', 3: 'Jess'}
print(type(dict)) # class 'dict'
# create a dictionary using a dict class
dict2 = dict({1: "John", 2: "Jenny", 3: "Jess"})
# display dictionary
print(dict2) # {1: 'John', 2: 'Jenny', 3: 'Jess'}
print(type(dict2)) # class 'dict'
# access value using a key name
print(dict2[1]) # John
# change the value of a key
dict2[1] = "Johnson"
print(dict2[1]) # Johnson
Set data type
In Python, a set is an unordered collection of data items that are unique. In other words, Python Set is a collection of elements (or objects) that contains no duplicate elements.
In Python, the set data type used to represent a group of unique elements as a single entity. For example, if we want to store student ID numbers, we can use the set datat type.
The set data type in Python is represented using a set class.
We can create a set using the two ways:
- By enclosing values in the curly brackets { }
- Using a set() class.
The set data type has the following characteristics:
- It is mutable which means we can change set items.
- Duplidate elements are not allowed.
- Heterogeneous (values of all data types) elements are allowed.
- Insertion order of elements is not preserved, so we can't perform indexing on a set.
Example set creation and manipulation
# create a set using curly brackets {,}
set = {10, 20, "John"}
print(set) # {10, 20, 'John'}
print(type(set)) # class 'set'
# create a set using set class
set2 = set({10, 20, "Jenny"})
print(set2) # {10, 20, 'Jenny'}
print(type(set2)) # class 'set'
# add element to set
set2.add(30)
print(set2) # {10, 20, 'Jenny', 30}
# remove element from set
set2.remove(10)
print(set2) # {20, 'Jenny', 30}