Python Collections – The unordered and unindexed data structures

In our previous article on Python Sequences, we saw the different types of sequences like lists, tuples, strings, byte arrays, and range. They all have a specific ordering of elements. Now today we are going to learn about Python Collections. These include sets and dictionaries, so let’s get started.

Python Collections

Unlike sequences, Python collections do not have any order. They are unordered and unindexed data structures. This means that it is not necessary to get the order in which we insert items.

Types of Python Collections

Python collections consist of Set and Dictionary.

Python Sets

The sets data structure in Python is inspired by the mathematical sets concept. A set is a collection of distinct elements, so we don’t have any duplicates in a set.

We can declare a set by separating values with commas inside curly braces {} or by using the set() function. To create an empty set, you must use set().

Code:

setA = {1,2,3,4,5,4}
setB = set({10,20,30,20,30})
setC = set()

print(setA)
print(setB)
print(setC)

Output:

{1,2,3,4,5}
{10,20,30}
set()

Sets is a mutable data structure so you can add, update, or remove elements from the set. But a set cannot contain lists, dictionary or sets.

Code:

setA = {1,4,5,2}
setA.remove(5)
print( setA)

Output:

{1,2,3,4}

Get the detailed insights about set with TechVidvan’s Python sets article.

Python Dictionary

Python dictionaries are an unordered collection of objects that holds value in a key-value structure. The key should be unique and must be an immutable object like a number, strings, and tuples. The values can be any Python object.

We can declare the Python dictionary in two ways.

Code:

dict1 = { 1: ”One”, 2: ”Two”, 3: ”Three”}

dict2 = dict()
dict2[1] = “One”
dict2[2] = “Two”
dict2[3] = “Three”

print(dict1)
print(dict2)

Output:

{1: ‘One’, 2: ‘Two’, 3: ‘Three’}
{1: ‘One’, 2: ‘Two’, 3: ‘Three’}

The main purpose of a dictionary is to map unique keys with a value so that retrieving information is optimized when we know the key. Dictionaries are mutable and we can simply add new key-value pairs in the dictionary by assigning them.

Code:

d = {“Shrangi”: [1, “PCM”], “Akshay”: [2,”PCB”], “Himanshu”: [3, “Arts”]}
d[“Ayushi”] = [4,”Commerce”]
print(d)

Output:

{‘Shrangi’: [1, ‘PCM’], ‘Akshay’: [2, ‘PCB’], ‘Himanshu’: [3, ‘Arts’]}
{‘Shrangi’: [1, ‘PCM’], ‘Akshay’: [2, ‘PCB’], ‘Himanshu’: [3, ‘Arts’], ‘Ayushi’: [4, ‘Commerce’]}