Type of Collections
We will study following collections in Python in this lesson:
- OrderedDict
- defaultdict
- counter
- namedtuple
- deque
OrderedDict
When order of insertion of the key and value matters for the program, we should make use of OrderedDict collection. Also, when the value for the same key is inserted, last value is overwritten with the new value. Let us take a look at a sample program:
author = OrderedDict([
(1, ‘David’),
(2, ‘Shubham’),
(3, ‘Swapnil Tirthakar’),
])
for num, name in author.items():
print(num, name)
Here is what we get back with this command:
defaultdict
Next collection in Python is defaultdict. This collection can contain duplicate keys. The main advantage of this collection is that we can collect values which belong to the identical keys. Let’s look at a program which demonstrates the same:
grade = [
(‘Shubham’, ‘B’),
(‘David’, "A"),
(‘LinuxHint’, ‘B’),
(‘LinuxHint’, ‘A’)
]
dict_grade = defaultdict(list)
for key, value in grade:
dict_grade[key].append(value)
print(list(dict_grade.items()))
Let’s see the output for this command:
Here, the items related to same key LinuxHint were collected and shown in the output as together.
counter
The Counter collections allow us to count all the values which are present in the collection against the same key. Here is a program to show how the counter collection works:
marks_collect = [
(‘Shubham’, 72),
(‘David’, 99),
(‘LinuxHint’, 91),
(‘LinuxHint’, 100)
]
counted = Counter(name for name, marks in marks_collect)
print(counted)
Here is what we get back with this command:
This provides a very easy way to count items in a Puython collection.
namedtuple
We can also have collection of items where values are assigned to a named key. This way, it is easy to access a value which is assigned to a name instead of an index. Let us look at an example:
Person = collections.namedtuple(‘Person’, ‘name age gender’)
oshima = Person(name=‘Oshima’, age=25, gender=‘F’)
print(oshima)
print(‘Name of Person: {0}’.format(oshima.name))
Let’s see the output for this command:
deque
As a final example, we can maintain a collection of items and remove characters form it as a deque process. Let us look at an example for the same:
person = collections.deque(‘Oshima’)
print(‘Deque :’, person)
print(‘Queue Length:’, len(person))
print(‘Left part :’, person[0])
print(‘Right part :’, person[–1])
person.remove(‘m’)
print(‘remove(m):’, person)
Here is what we get back with this command:
Conclusion
In this lesson, we looked at various collections used in Python and what each collection offers as a different capability.