Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Python Collections

Introduction to Python Collections

Python is an interpreted and object-oriented high-level programming language, first released in 1991.

Why do people consider python?

  1. Programmer friendliness and ease to understand
  2. Extensive support libraries
  3. Good flexibility
  4. platform portability (Ability to scalable across any platforms)
  5. 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. For accessing this datatypes object declarations are expected.

The key collection modules in python are listed below,

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 which is 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

Ex:

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)])

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,

Ex:

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

Deque:

In python collections, deque represents a queue which 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

Ex:

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', '#'])

NamedTuple:

Named tuples are very closely related to the dictionary because as like 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.

Ex:

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 discuss the different collection of python with key functions and examples. You can also go through our other suggested articles to learn more –

  1. What Is Python
  2. Python Operators
  3. Python String Functions
  4. Python Alternatives

The post Python Collections appeared first on EDUCBA.



This post first appeared on Best Online Training & Video Courses | EduCBA, please read the originial post: here

Share the post

Python Collections

×

Subscribe to Best Online Training & Video Courses | Educba

Get updates delivered right to your inbox!

Thank you for your subscription

×