Introduction to Python Collections
In Python, collections are containers used to store data collections, including list, set, tuple, etc. The entities are the built-in components having various collection modules such as Counter OrderedDict, ChainMap, enum, etc. Enum ere introduced in Python to enhance the functionalities of the built-in containers that also have additional data structures to store data collections and assist in operations like appending to nested lists inside a dictionary, keeping entries sorted when inserted, etc.
Why do people consider python?
- Programmer friendliness and ease in understanding
- Extensive support libraries
- Good flexibility
- platform portability (Ability to scalable across any platforms)
- Opensource availability
Python Collections
Collections are data types that are shipped into python under the collection module. it holds a large number of containers which are largely useful. these collections are object driven since they are pulled from a separate module called collections. Thus, for accessing these datatypes, object declarations are expected.
The key collection modules in python are listed below,
1. OrderedDict
Order dict is very similar to normal Dict, except it is more efficient for reordering operations. The ordered dictionary maintains its sequence of insertion very strictly. some among the protocols of the ordered dictionary are below,
- When a key that is the same as the existing key is inserted, the ordered dictionary collection replaces the existing key with the new key
- deleting an entry and reinserting it inserts the new entry as the last item
- The usual dict was intended to be extremely first-class at mapping operations.
- Algorithmically, OrderedDict is able to grip the recurrent rearrangement process well again than dict.
The key functions used in a dictionary are as below
Functions | Description |
Python Dictionary clear() | Removes all Items |
Python Dictionary copy() | Returns Shallow Copy of a Dictionary |
Python Dictionary fromkeys() | Creates a dictionary from a given sequence |
Python Dictionary get() | Find the value of a key |
Python Dictionary items() | returns view of dictionary’s (key, value) pair |
Python Dictionary keys() | Prints the keys |
Python Dictionary popitem() | Remove the last element of the dictionary |
Python Dictionary setdefault() | Inserts Key With a Value if Key is not Present |
Python Dictionary pop() | removes and returns element having given key |
Python Dictionary values() | returns view of all values in the dictionary |
Python Dictionary update() | Updates the Dictionary |
Example:
from collections import OrderedDict
o=OrderedDict()
p=OrderedDict({'a':1,'b':2})
o['a']=3
o['b']=2
o['c']=1
o.popitem()
print('print the keys :', o.keys())
print('print the Values :', o.values())
print("Value of key a = ", o.get('a'))
print(p)
Output:
print the keys : odict_keys([‘a’, ‘b’])
print the Values : odict_values([3, 2])
Value of key a = 3
OrderedDict([(‘a’, 1), (‘b’, 2)])
2. Counter
This is another container of the dict subclass which is used to keep hold of the count of occurrences of all values in the container.some of the initialization techniques of the counter are below,
Example:
from collections import Counter
a=(1,2,3,1)
b=[1,2,3]
c={1,2,3,1}
d={'1':'anand','2':'kumar','3':'ravi'}
e='anand'
print('Count of a : ',Counter(a))
print('Count of b : ',Counter(b))
print('Count of c : ',Counter(c)) #sets do not allow duplicates
print('Count of d : ',Counter(d))
print('Count of e : ',Counter(e)) #counter on string
print('print most common value in a :'a.most_common(1))
Output:
Count of a : Counter({1: 2, 2: 1, 3: 1})
Count of b : Counter({1: 1, 2: 1, 3: 1})
Count of c : Counter({1: 1, 2: 1, 3: 1})
Count of d : Counter({‘3’: ‘ravi’, ‘2’: ‘kumar’, ‘1’: ‘anand’})
Count of e : Counter({‘a’: 2, ‘n’: 2, ‘d’: 1})
print most common value in a : 1
Points to ponder:
- Using counter on the dictionary is considered as manual initiation of count values to the keys mentioned
- element() method is used for iteration on counter
- most_common() is used for finding the value with the most number of frequencies
3. Deque
In python collections, deque represents a queue that is double-ended and which allows values to be added to both the front and rear of the queue. Operations allowed in a double-ended queue are as below,
- append() – Append value to the right
- appendleft() – append value to the left
- pop() – delete value to the right end
- popleft() – delete value to the left end
Example:
import collections
a=collections.deque('anand')
b=collections.deque((1,2,2))
c=collections.deque({1,2,3,1})
print('Queue_a',a)
print('Queue_b',b)
print('Queue_c',c)
a.append('#')
a.appendleft('#')
print('After append :',a)
b.pop()
b.popleft()
print('After Removal :'b)
c.clear()
print('After clearing the Queue :',c)
Output:
Queue_a deque([‘a’, ‘n’, ‘a’, ‘n’, ‘d’])
Queue_b deque([1, 2, 2])
Queue_c deque([1, 2, 3])
After append : deque([‘#’, ‘a’, ‘n’, ‘a’, ‘n’, ‘d’, ‘#’])
4. NamedTuple
Named tuples are very closely related to the dictionary because dictionaries here to keys are tagged with values. The key difference between dictionaries and named tuples are these named tuples allow accessing its elements as both key-value and iteration. key operations performed with named tuples are as below,
Here the attribute values can be accessed through indexes, whereas dictionaries do not allow the same.
Example:
Point = namedtuple('Point', ['x', 'y'])
p = Point(11, y=22) # instantiate with positional or keyword arguments
p[0] + p[1] # indexable like the plain tuple (11, 22)
Output :
33
Conclusion
Python being a language with extensive libraries, the collection acts as one among them, which largely works as an upscale menu in the collection datatype.
Recommended Articles
This is a guide to Python Collections. Here we have discussed basic concepts, different collections of python with examples in detail. You can also go through our other suggested articles to learn more –
40 Online Courses | 13 Hands-on Projects | 215+ Hours | Verifiable Certificate of Completion
4.8
View Course
Related Courses