What are Python Data Types? Illustrated with Examples!

python data types

Python is one of the most popular programming languages that is used for various purposes such as software development, web development, mathematics, system scripting, etc. Created in the year 1991 by Guido van Rossum, Python is among the trusted programming languages for software developers, engineers and researchers of various other fields.

You can use Python to connect database systems, to handle big data and carry out complex mathematics, to create web applications, etc. Python works on different platforms such as Windows, Linux, Mac, Raspberry pi, etc. It has got a simple syntax, which is very similar to the English language. So, you will not get confused about understanding the codes and syntax. Using its syntax. Developers write programs in fewer lines as compared to other programming languages.

Some more interesting information about this programming language is that it runs on an interpreter system. This suggests that the code can be easily executed as soon as it is written, which further indicates that the prototyping in Python is real quick.

In this blog, we have discussed the different Python data types. We hope you get a good insight into what they are and how they are used in coding.

Python Data Types

As you are here reading this blog, we assume you have prior knowledge about the programming knowledge, Python. However, we will start with defining data types. Data types are the categorization or classification of data items. It is the way of representing the kind of value that describes what operations can be carried out on specific data. As everything on Python programming is an object, its data types are basically classes and variables are object (instance) of these classes.

Here are the built-in or standard Python data types:

  • Numeric
  • Sequence Type
  • Boolean
  • Set
  • Dictionary

Now let’s look into these in detail. Read on.

Numeric

The first data type on our list is numeric. This data type in Python represents the data with a numeric value. It can be a floating number, an integer or complex numbers. The values of a numeric are defined as ‘float’, ‘int’ and ‘complex’ class in Python.

Integers: It is a numeric value represented by ‘int’ class. It can be negative or positive whole numbers. Python doesn’t have a definite limit to the length of an integer value. However, it can’t be in decimal or fraction, always a whole number.

Float: It is a numeric value represented by ‘float’ class. It is defined as a real number having floating-point representation. The value is specified by a decimal point. Sometimes, the character E or e followed by a negative or positive integer can possibly be appended to represent scientific notation.

Complex numbers: The value is represented by ‘complex’ class. It is always specified as (real part) + (imaginary part)j.

Example: 4+5j

Note: type () function is to determine the kind of data type

# Python program to

# demonstrate numeric value

a = 5

print("Type of a: ", type(a))

b = 5.0

print("\nType of b: ", type(b))

c = 2 + 4j

print("\nType of c: ", type(c))

Output:

Type of a:  <class 'int'>

Type of b:  <class 'float'>

Type of c:  <class 'complex'>

Sequence

Coming to sequence, it is the ordered collection of different or identical data types. The sequences are a data type of Python that allows you to store more than one value in an arranged and efficient way.

A sequence is further divided into three types in Python – String, List and Tuple.

String

In Python programming, Strings are a series of bytes that represent Unicode characters. It is a collection of multiple characters inserted in a single quote, double-quote or triple quote. There is no character data type in Python, instead, it is a string of length one. A string is represented by ‘str’ class.

How to create a string

You can create strings in Python using single, double or triple quotes.

# Python Program for

# Creation of String# Creating a String

# with single Quotes

String1 = 'Welcome to the Robots World'

print("String with the use of Single Quotes: ")

print(String1)

# Creating a String

# with double Quotes

String1 = "I'm a Robot"

print("\nString with the use of Double Quotes: ")

print(String1)

print(type(String1))

# Creating a String

# with triple Quotes

String1 = '''I'm a Robot and I live in a world of "Robots"'''

print("\nString with the use of Triple Quotes: ")

print(String1)

print(type(String1))

# Creating String with triple

# Quotes allows multiple lines

String1 = '''Robots

For

Life'''

print("\nCreating a multiline String: ")

print(String1)

Output:

String with the use of Single Quotes:

Welcome to the Robots World

String with the use of Double Quotes:

I’m a Robot

<class 'str'>

String with the use of Triple Quotes:

I’m a Robot and I live in a world of “Robots”

<class 'str'>

Creating a multiline String:

Robots

For

Life

How to access elements of string

In Python programming, you can access individual characters of a string with the method of Indexing. Indexing is a method that allows negative access references to access characters from the back of the String.

Example: 1 refers to the last character; 2 refers to the second last character; 3 refers to the third last character and so on.

While you access an index out of the range, it will cause an ‘IndexError’. It only allows integers to pass as an index. Float and other types will result in an ‘IndexError’.

# Python Program to Access

# characters of String

String1 = "RobotsForRobots"

print("Initial String: ")

print(String1)

# Printing First character

print("\nFirst character of String is: ")

print(String1[0])

# Printing Last character

print("\nLast character of String is: ")

print(String1[-1])

 

Output:

Initial String:

RobotsForRobots

 

First character of String is:

R

 

Last character of String is:

s

 

Deleting or Updating from a String

Python doesn’t allow the deletion or updation of characters from a String. It will result in an error as the programming language doesn’t support item deletion or item assignment from a String.

The reason behind this is the Strings are immutable. So, elements of a String can’t be altered once it has been assigned. You can only reassign new strings to the same name.

# Python Program to Update / delete

# character of a String

String1 = "Hello, I'm a Robot"

print("Initial String: ")

print(String1)

# Updating a character

# of the String

String1[2] = 'p'

print("\nUpdating character at 2nd Index: ")

print(String1)

# Deleting a character

# of the String

del String1[2]

print("\nDeleting character at 2nd Index: ")

print(String1)

 Output:

Traceback (most recent call last):

File “/home/360bb1830c83a918fc78aa8979195653.py”, line 10, in

String1[2] = ‘p’

TypeError: ‘str’ object does not support item assignment

 

Traceback (most recent call last):

File “/home/499e96a61e19944e7e45b7a6e1276742.py”, line 10, in

del String1[2]

TypeError: ‘str’ object doesn’t support item deletion

Escape sequencing in Python

It is not allowed to print Strings with single and double quotes as it causes ‘SyntaxError’. This happens because String already consists of single and double-quotes. So, you need to use either triple quotes to print a String or escape sequences.

Escape sequences start with a backlash and can be differently interpreted. If you use single quotes to represent a string, all the single quotes are escaped and the same happens in case of using double-quotes.

# Python Program for

# Escape Sequencing

# of String

# Initial String

String1 = '''I'm a "Robot"'''

print("Initial String with use of Triple Quotes: ")

print(String1)

# Escaping Single Quote

String1 = 'I\'m a "Robot"'

print("\nEscaping Single Quote: ")

print(String1)

# Escaping Doule Quotes

String1 = "I'm a \"Robot\""

print("\nEscaping Double Quotes: ")

print(String1)

# Printing Paths with the

# use of Escape Sequences

String1 = "C:\\Python\\Robots\\"

print("\nEscaping Backslashes: ")

print(String1)

Output:

Initial String with use of Triple Quotes:

I’m a “Robot”

 

Escaping Single Quote:

I’m a “Robot”

 

Escaping Double Quotes:

I’m a “Robot”

 

Escaping Backslashes:

C:\Python\Robots\

 

List

List are nothing but arrays, declared in different languages. Lists need not be necessarily homogenous and this  akes it the strongest tool in Python. A single list consists of Python data types like strings, integers and objects. These are mutable and thus, you can alter them after their creation.

In Python, lists are ordered and have a fixed count. The elements of a list are indexed based on the definite sequence and its indexing is done with 0 as the first index.

Each element in a list holds a definite place. It allows duplicating of elements in the list, maintaining the distinct place of each element along with their credibility. A list is represented by ‘list’ class.

How to create a list

In Python programming, lists can be created by simply placing the sequence inside the square brackets []. Contrary to Sets (discussed later in the blog), list doesn’t need to have a built-in function for its creation.

# Python program to demonstrate

# Creation of List

 

# Creating a List

List = []

print(“Intial blank List: “)

print(List)

 

# Creating a List with

# the use of a String

List = [‘RobotsForRobots’]

print(“\nList with the use of String: “)

print(List)

 

# Creating a List with

# the use of multiple values

List = [“Robots”, “For”, “Robots”]

print(“\nList containing multiple values: “)

print(List[0])

print(List[2])

 

# Creating a Multi-Dimensional List

# (By Nesting a list inside a List)

List = [[‘Robots’, ‘For’], [‘Robots’]]

print(“\nMulti-Dimensional List: “)

print(List)

Output:

Intial blank List:

[]

 

List with the use of String:

[‘RobotsForRobots’]

 

List containing multiple values:

Robots

Robots

 

Multi-Dimensional List:

[[‘Robots’, ‘For’], [‘Robots’]]

 

How to add elements to a list

You can add elements to the list by using the inbuilt function – ‘append()’. It is possible to add only one element at a time to the list using this inbuilt function

To add the element at the desired position, you can use ‘insert()’ method. Other than these two methods, there’s the third method to add elements to the list – ‘extend()’. You can use this method to add multiple elements at the same time at the end of the list.

# Python program to demonstrate

# Addition of elements in a List

 

# Creating a List

List = []

print(“Initial blank List: “)

print(List)

 

# Addition of Elements

# in the List

List.append(1)

List.append(2)

List.append(4)

print(“\nList after Addition of Three elements: “)

print(List)

 

# Addition of Element at

# specific Position

# (using Insert Method)

List.insert(3, 12)

List.insert(0, ‘Robots’)

print(“\nList after performing Insert Operation: “)

print(List)

 

# Addition of multiple elements

# to the List at the end

# (using Extend Method)

List.extend([8, ‘Robots’, ‘Always’])

print(“\nList after performing Extend Operation: “)

print(List)

Output:

Initial blank List:

[]

 

List after Addition of Three elements:

[1, 2, 4]

 

List after performing Insert Operation:

[‘Robots’, 1, 2, 4, 12]

 

List after performing Extend Operation:

[‘Robots’, 1, 2, 4, 12, 8, ‘Robots’, ‘Always’]

 

How to access elements from the list

To access elements from the list, you need to refer to the index number. Use the index operator [ ] to access an element in the list. However, amke sure the index is an integer. You can access nested list using nested indexing.

In Python, negative sequence indexes are representations of positions from the end of the array. Rather than computing the offset as in ‘List[len(list)-3]’, you can simply write List[-3]. Negative indexing means starting from the end. -1 indicates the last item, -2 indicates the second last item and so on.

# Python program to demonstrate

# accessing of element from list

 

# Creating a List with

# the use of multiple values

List = [“Robots”, “For”, “Robots”]

 

# accessing a element from the

# list using index number

print(“Accessing element from the list”)

print(List[0])

print(List[2])

 

# accessing a element using

# negative indexing

print(“Accessing element using negative indexing”)

 

# print the last element of list

print(List[-1])

 

# print the third last element of list

print(List[-3])

 

Output:

Accessing element from the list

Robots

Robots

Accessing element using negative indexing

Robots

Robots

How to remove elements from the list

You can remove elements from the list by the built-in function ‘remove()’. But, if the element doesn’t exist in the list, you will find an error. To remove and return an element from the list, you can use ‘pop()’ function. However, it removes only the last element of the list by default. In case you wish to remove an element from a particular position of the list, pass the index of the element as an argument to the ‘pop()’ method.

# Python program to demonstrate

# Removal of elements in a List

 

# Creating a List

List = [1, 2, 3, 4, 5, 6,

7, 8, 9, 10, 11, 12]

print(“Intial List: “)

print(List)

 

# Removing elements from List

# using Remove() method

List.remove(5)

List.remove(6)

print(“\nList after Removal of two elements: “)

print(List)

 

List.pop()

print(“\nList after popping an element: “)

print(List)

 

# Removing element at a

# specific location from the

# Set using the pop() method

List.pop(2)

print(“\nList after popping a specific element: “)

print(List)

 

Output:

Intial List:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

 

List after Removal of two elements:

[1, 2, 3, 4, 7, 8, 9, 10, 11, 12]

 

List after popping an element:

[1, 2, 3, 4, 7, 8, 9, 10, 11]

 

List after popping a specific element:

[1, 2, 4, 7, 8, 9, 10, 11]

Tuple

Tuple is an ordered collection of the objects in Python and is very similar to a list. The sequence of the values stored in a tuple can be of different types. They are indexed using integers. One significant difference between a tuple and a list is that tuples are immutable, whereas the list is mutable. Also, lists are not hashable but tuples are. A tuple is represented by ‘tuple’ class.

How to create a tuple

In Python programming, tuples are created by placing a sequence of values separated by ‘,’. You can either use or not use the parentheses to group the data sequence. They can be of any data type, consisting of any number of elements.

It is also possible to create tuples using a single element, but it is a little complicated.

It is not sufficient to have one element in the parentheses and there must be a ‘,’ to make it a tuple. When you create a tuple in Python without using parentheses, it is called Tuple Packing.

# Python program to demonstrate

# creation of Set

 

# Creating an empty tuple

Tuple1 = ()

print(“Initial empty Tuple: “)

print (Tuple1)

 

# Creating a Tuple with

# the use of Strings

Tuple1 = (‘Robots’, ‘For’)

print(“\nTuple with the use of String: “)

print(Tuple1)

 

# Creating a Tuple with

# the use of list

list1 = [1, 2, 4, 5, 6]

print(“\nTuple using List: “)

print(tuple(list1))

 

# Creating a Tuple with the

# use of built-in function

Tuple1 = tuple(‘Robots’)

print(“\nTuple with the use of function: “)

print(Tuple1)

 

# Creating a Tuple

# with nested tuples

Tuple1 = (0, 1, 2, 3)

Tuple2 = (‘python’, ‘Robot’)

Tuple3 = (Tuple1, Tuple2)

print(“\nTuple with nested tuples: “)

print(Tuple3)

Output:

Initial empty Tuple:

()

 

Tuple with the use of String:

(‘Robots’, ‘For’)

 

Tuple using List:

(1, 2, 4, 5, 6)

 

Tuple with the use of function:

(‘R’, ‘o’, ‘b’, ‘o’, ‘t’, ‘s’)

 

Tuple with nested tuples:

((0, 1, 2, 3), (‘python’, ‘robot’))

 

How to access an element of a tuple

To access the tuple elements, you need to refer to the index number. You need to use the index operator [ ] to access an element in s tuple. Remember, the index must be an integer. Nested tuples are accessed using nested indexing.

 

# Python program to

# demonstrate accessing tuple

 

tuple1 = tuple([1, 2, 3, 4, 5])

 

# Accessing element using indexing

print(“Frist element of tuple”)

print(tuple1[0])

 

# Accessing element from last

# negative indexing

print(“\nLast element of tuple”)

print(tuple1[-1])

 

print(“\nThird last element of tuple”)

print(tuple1[-3])

 

Output:

Frist element of tuple

1

 

Last element of tuple

5

 

Third last element of tuple

3

How to duplicate or update elements of a tuple

In Python programming, you cannot update or duplicate a tuple. If you try doing so, it will cause an error. It is because tuples are immutable. SO, you cannot change the elements of a tuple once it is assigned. You can only create new tuples and reassign them to the same name.

# Python program to

# demonstrate updation / deletion

# from a tuple

 

tuple1 = tuple([1, 2, 3, 4, 5])

print(“Initial tuple”)

print(tuple1)

 

# Updating an element

# of a tuple

tuple1[0] = -1

print(tuple1)

 

# Deleting an element

# from a tuple

del tuple1[2]

print(tuple1)

 

Output:

Traceback (most recent call last):

File “/home/084519a8889e9b0103b874bbbb93e1fb.py”, line 11, in

tuple1[0] = -1

TypeError: ‘tuple’ object does not support item assignment

 

Traceback (most recent call last):

File “/home/ffb3f8be85dd393bde5d0483ff191343.py”, line 12, in

del tuple1[2]

TypeError: ‘tuple’ object doesn’t support item deletion

 

Boolean

The third Python data type on the list is Boolean. It is a data type having one of the two built-in values – ‘true’ or ‘false’. The boolean objects that are equal to true are truthy (true) and the ones equal to false are falsy (false). However, you can also evaluate non-boolean objects in Boolean context and identify them as true or false. The Boolean data type is represented by the ‘bool’ class.

Note: True and False with a capital ‘T’ and ‘F’ are valid booleans otherwise python will throw an error.

# Python program to

# demonstrate boolean type

 

print(type(True))

print(type(False))

 

print(type(true))

Output:

<class ‘bool’>

<class ‘bool’>

Traceback (most recent call last):

File “/home/7e8862763fb66153d70824099d4f5fb7.py”, line 8, in

print(type(true))

NameError: name ‘true’ is not defined

 

Set

In Python, Set is an unordered collection of data type that is mutable, iterable and has got no duplicate elements. The order of elements in a set is always undefined. But, it may consist of various elements. One of the main benefits of using a set instead of a list is that it has got a perfectly optimized method to check if there is a specific element present in the set.

How to create a set

You can create sets by using the built-in set() function. It takes an iterable object or a sequence by inserting the sequence inside curly braces and separate them by a ‘,’. A set consists of only unique elements, but you can pass multiple duplicate values at the time of creating a set.

The order of elements in a set is undefined and also unchangeable. The type of elements in a set is not necessarily the same. You can also pass mixed-up data type values to the set.

# Python program to demonstrate

# Creation of Set in Python

 

# Creating a Set

set1 = set()

print(“Intial blank Set: “)

print(set1)

 

# Creating a Set with

# the use of a String

set1 = set(“RobotsForRobots”)

print(“\nSet with the use of String: “)

print(set1)

 

# Creating a Set with

# the use of a List

set1 = set([“Robots”, “For”, “Robots”])

print(“\nSet with the use of List: “)

print(set1)

 

# Creating a Set with

# a mixed type of values

# (Having numbers and strings)

set1 = set([1, 2, ‘Robots’, 4, ‘For’, 6, ‘Robots’])

print(“\nSet with the use of Mixed Values”)

print(set1)

Output:

Intial blank Set:

set()

 

Set with the use of String:

{‘F’, ‘o’, ‘R’, ‘s’, ‘b’, ‘t’, ‘e’}

 

Set with the use of List:

{‘Robots’, ‘For’}

 

Set with the use of Mixed Values

{1, 2, 4, 6, ‘Robots’, ‘For’}

 

How to add elements to a set

You can add elements to a set by the built-in ‘add()’ function. To add a single element to a set at a time using the ‘add()’ method. However, if you want to add multiple elements to a set, use ‘Update()’ method.

# Python program to demonstrate

# Addition of elements in a Set

 

# Creating a Set

set1 = set()

print(“Intial blank Set: “)

print(set1)

 

# Adding element and tuple to the Set

set1.add(8)

set1.add(9)

set1.add((6, 7))

print(“\nSet after Addition of Three elements: “)

print(set1)

 

# Addition of elements to the Set

# using Update function

set1.update([10, 11])

print(“\nSet after Addition of elements using Update: “)

print(set1)

Output:

Intial blank Set:

set()

 

Set after Addition of Three elements:

{8, 9, (6, 7)}

 

Set after Addition of elements using Update:

{8, 9, 10, 11, (6, 7)}

 

How to access a set

You cannot access an element of a set by referring to an index. It is because these are unordered and the elements have no index. But, you can always loop through the set elements used for loop or just ask if a particular value is there in a set by using the ‘in’ method.

# Python program to demonstrate

# Accessing of elements in a set

 

# Creating a set

set1 = set([“Robots”, “For”, “Robots”])

print(“\nInitial set”)

print(set1)

 

# Accessing element using

# for loop

print(“\nElements of set: “)

for i in set1:

print(i, end =” “)

 

# Checking the element

# using in keyword

print(“Robots” in set1)

Output:

Initial set:

{‘Robotss’, ‘For’}

 

Elements of set:

Robots For

 

True

 

How to remove elements from a set

You can remove elements from a set with the help of the ‘remove()’ function. But, if the element you want to remove is not present in the set, Python will show a KeyError. In order to remove an element from a set without theKeyError, you need to use the ‘discard()’ function.

You can also use the ‘pop()’ function to remove and return an element from a set. Remember, it only removes the last element from the set. You must use the ‘clear()’ function to remove all the elements from the set.

# Python program to demonstrate

# Deletion of elements in a Set

 

# Creating a Set

set1 = set([1, 2, 3, 4, 5, 6,

7, 8, 9, 10, 11, 12])

print(“Intial Set: “)

print(set1)

 

# Removing elements from Set

# using Remove() method

set1.remove(5)

set1.remove(6)

print(“\nSet after Removal of two elements: “)

print(set1)

 

# Removing elements from Set

# using Discard() method

set1.discard(8)

set1.discard(9)

print(“\nSet after Discarding two elements: “)

print(set1)

 

# Removing element from the

# Set using the pop() method

set1.pop()

print(“\nSet after popping an element: “)

print(set1)

 

# Removing all the elements from

# Set using clear() method

set1.clear()

print(“\nSet after clearing all the elements: “)

print(set1)

Output:

Intial Set:

{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}

 

Set after Removal of two elements:

{1, 2, 3, 4, 7, 8, 9, 10, 11, 12}

 

Set after Discarding two elements:

{1, 2, 3, 4, 7, 10, 11, 12}

 

Set after popping an element:

{2, 3, 4, 7, 10, 11, 12}

 

Set after clearing all the elements:

set()

Dictionary

The last on the list of Python data types, which is an unordered collection of data values. It is used to store data values like a map. Unlike other data types described in this blog having only a single value as an element, a dictionary holds ‘key:value’ pair. Key:value is provided in the dictionary to perfectly optimize it.

In a dictionary, each key value is separated by a ‘:’ and each key is separated by a ‘,’.

How to create a dictionary

In Python, you can create a dictionary by placing a sequence of elements within curly braces {}, separated by ‘,’. A dictionary holds a pair of value – one called the key and the other referred to as its ‘key:value’,

Values in a dictionary can be of any data type (integers, strings, etc.). The values can be duplicated, but the keys are immutable and cannot be repeated.

Another way of creating a dictionary is by using the built-in ‘dict()’ function. You can also create an empty dictionary by placing curly braces.

Note: Dictionary keys are case sensitive. So, if you create dictionaries with the same name but in different cases, it will be treated distinctly.

# Creating an empty Dictionary

Dict = {}

print(“Empty Dictionary: “)

print(Dict)

 

# Creating a Dictionary

# with Integer Keys

Dict = {1: ‘Robots’, 2: ‘For’, 3: ‘Robots’}

print(“\nDictionary with the use of Integer Keys: “)

print(Dict)

 

# Creating a Dictionary

# with Mixed keys

Dict = {‘Name’: ‘Robots’, 1: [1, 2, 3, 4]}

print(“\nDictionary with the use of Mixed Keys: “)

print(Dict)

 

# Creating a Dictionary

# with dict() method

Dict = dict({1: ‘Robots’, 2: ‘For’, 3:’Robots’})

print(“\nDictionary with the use of dict(): “)

print(Dict)

 

# Creating a Dictionary

# with each item as a Pair

Dict = dict([(1, ‘Robots’), (2, ‘For’)])

print(“\nDictionary with each item as a pair: “)

print(Dict)

Output:

Empty Dictionary:

{}

 

Dictionary with the use of Integer Keys:

{1: ‘Robots’, 2: ‘For’, 3: ‘Robots’}

 

Dictionary with the use of Mixed Keys:

{1: [1, 2, 3, 4], ‘Name’: ‘Robots’}

 

Dictionary with the use of dict():

{1: ‘Robots’, 2: ‘For’, 3: ‘Robots’}

 

Dictionary with each item as a pair:

{1: ‘Robots’, 2: ‘For’}

 

How to add elements to a dictionary

In a Python Dictionary, you can add elements in various methods. You can easily add one value at a time to the Dictionary by defining a value along with the key. For example: Dict[Key] = ‘Value’.

To update an existing value in a dictionary, you can use the built-in ‘update()’ method.

Note: When adding a value to a Python Dictionary, if the key-value already exists, the value will get successfully updated. Or else, a new Key with that value will be added to the Dictionary.

# Creating an empty Dictionary

Dict = {}

print(“Empty Dictionary: “)

print(Dict)

 

# Adding elements one at a time

Dict[0] = ‘Robots’

Dict[2] = ‘For’

Dict[3] = 1

print(“\nDictionary after adding 3 elements: “)

print(Dict)

 

# Updating existing Key’s Value

Dict[2] = ‘Welcome’

print(“\nUpdated key value: “)

print(Dict)

Output:

Empty Dictionary:

{}

 

Dictionary after adding 3 elements:

{0: 'Robots', 2: 'For', 3: 1}

 

Updated key value:

{0: 'Robots', 2: 'Welcome', 3: 1}

How to access elements from a Dictionary

If you want to access the items of a dictionary, you must refer to its key name. You can use Key inside square brackets ‘[]’. Another method of accessing elements from a dictionary is the ‘get()’ method.

Example:

# Python program to demonstrate

# accessing a element from a Dictionary

# Creating a Dictionary

Dict = {1: 'Robots', 'name': 'For', 3: 'Robotss'}

# accessing a element using key

print("Accessing a element using key:")

print(Dict['name'])

# accessing a element using get()

# method

print("Accessing a element using get:")

print(Dict.get(3))

Output:

Accessing a element using key:

For

Accessing a element using get:

Robots

 

How to remove elements from a dictionary

In a Python Dictionary, the deletion of keys can be easily done using the ‘del’ keyword. By using this keyword, you can delete specific values form a dictionary and even the entire dictionary if needed.

Other functions that you can use to remove deleting arbitrary values and specific values are ‘popitem()’ and ‘pop()’ respectively.  To delete the entire dictionary (to delete all the items), you can use the ‘clear()’ method.

Example:

# Initial Dictionary

Dict = { 5 : 'Welcome', 6 : 'To', 7 : 'Robots',

'A' : {1 : 'Robots', 2 : 'For', 3 : 'Robots'},

'B' : {1 : 'Robots', 2 : 'Life'}}

print("Initial Dictionary: ")

print(Dict)

# Deleting a Key value

del Dict[6]

print("\nDeleting a specific key: ")

print(Dict)

# Deleting a Key

# using pop()

Dict.pop(5)

print("\nPopping specific element: ")

print(Dict)

# Deleting an arbitrary Key-value pair

# using popitem()

Dict.popitem()

print("\nPops an arbitrary key-value pair: ")

print(Dict)

# Deleting entire Dictionary

Dict.clear()

print("\nDeleting Entire Dictionary: ")

print(Dict)

Output:

Initial Dictionary:

{'B': {1: 'Robots', 2: 'Life'}, 'A': {1: 'Robots', 2: 'For', 3: 'Robots'},

5: 'Welcome', 6: 'To', 7: 'Robots'}

 

Deleting a specific key:

{'B': {1: 'Robots', 2: 'Life'}, 'A': {1: 'Robots', 2: 'For', 3: 'Robots'},

5: 'Welcome', 7: 'Robots'}

 

Popping specific element:

{'B': {1: 'Robots', 2: 'Life'}, 'A': {1: 'Robots', 2: 'For', 3: 'Robots'}, 7: 'Robots'}

 

Pops an arbitrary key-value pair:

{'A': {1: 'Robots', 2: 'For', 3: 'Robots'}, 7: 'Robots'}

 

Deleting Entire Dictionary:

{}

 

Conclusion

We hope you are now aware of all the data types of Python and can use it to practice the basic scripts of the programming language.

Must Know:  Red room dark web: What is it ? Who-why use the red room!

Leave a Reply

Read previous post:
mobile marketing success
5 Keys to Mobile Marketing Success for Small Businesses

It's official. Mobile has taken over as the preferred device when folks are accessing the Internet. Whether it's a smartphone,...

Close