Python Data Types

Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, data types are actually classes and variables are instance (object) of these classes.

Following are the standard or built-in data type of python:

Python-data-type



Numeric

In Python, numeric data type represent the data which has numeric value. Numeric value can be interger, floating number or even complex numbers. These values arre defined as int, float and complex class in Python.

  • Intergers – This value is represented by int class. It contains positive or negative whole numbers (without fraction or decimal). In Python there is no limit to how long an interger value can be.
  • Float – This value is represented by float class. It is a real number with floating point representation. It is specified by a decimal point. Optionally, the character e or E followed by a positive or negative integer may be appended to specify scientific notation.
  • Complex Numbers – Complex number is represented by complex class. It is specified as (real part) + (imaginary part)j. For example – 2+3j

Notetype() function is used to determine the type of data type.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

Type of a:  <class 'int'>

Type of b:  <class 'float'>

Type of c:  <class 'complex'>

Sequence Type

In Python, sequence is the ordered collection of similar or different data types. Sequences allows to store multiple values in an organized and efficient fashion. There are several sequence types in Python –

1) String

In Python, Strings are arrays of bytes representing Unicode characters. A string is a collection of one or more characters put in a single quote, double-quote or triple quote. In python there is no character data type, a character is a string of length one. It is represented by str class.

Creating a string

Strings in Python can be created using single quotes or double quotes or even triple quotes.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python Program for 
# Creation of String 
    
# Creating a String  
# with single Quotes 
String1 = 'Welcome to the Geeks World'
print("String with the use of Single Quotes: "
print(String1) 
    
# Creating a String 
# with double Quotes 
String1 = "I'm a Geek"
print("\nString with the use of Double Quotes: "
print(String1) 
print(type(String1))
    
# Creating a String 
# with triple Quotes 
String1 = '''I'm a Geek and I live in a world of "Geeks"'''
print("\nString with the use of Triple Quotes: "
print(String1) 
print(type(String1))
  
# Creating String with triple 
# Quotes allows multiple lines 
String1 = '''Geeks 
            For 
            Life'''
print("\nCreating a multiline String: "
print(String1) 

chevron_right


Output:

String with the use of Single Quotes: 
Welcome to the Geeks World

String with the use of Double Quotes: 
I'm a Geek
<class 'str'>

String with the use of Triple Quotes: 
I'm a Geek and I live in a world of "Geeks"
<class 'str'>

Creating a multiline String: 
Geeks 
            For 
            Life

Accessing elements of string

In Python, individual characters of a String can be accessed by using the method of Indexing. Indexing allows negative address references to access characters from the back of the String, e.g. -1 refers to the last character, -2 refers to the second last character and so on.
While accessing an index out of the range will cause an IndexError. Only Integers are allowed to be passed as an index, float or other types will cause a TypeError.

Python string indexing


filter_none

edit
close

play_arrow

link
brightness_4
code

# Python Program to Access 
# characters of String 
    
String1 = "GeeksForGeeks"
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]) 

chevron_right


Output:

Initial String: 
GeeksForGeeks

First character of String is: 
G

Last character of String is: 
s

Deleting/Updating from a String

In Python, Updation or deletion of characters from a String is not allowed. This will cause an error because item assignment or item deletion from a String is not supported. This is because Strings are immutable, hence elements of a String cannot be changed once it has been assigned. Only new strings can be reassigned to the same name.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python Program to Update / delete 
# character of a String 
    
String1 = "Hello, I'm a Geek"
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) 

chevron_right


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

While printing Strings with single and double quotes in it causes SyntaxError because String already contains Single and Double Quotes and hence cannot be printed with the use of either of these. Hence, to print such a String either Triple Quotes are used or Escape sequences are used to print such Strings.
Escape sequences start with a backslash and can be interpreted differently. If single quotes are used to represent a string, then all the single quotes present in the string must be escaped and same is done for Double Quotes.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python Program for 
# Escape Sequencing  
# of String 
    
# Initial String 
String1 = '''I'm a "Geek"'''
print("Initial String with use of Triple Quotes: "
print(String1) 
    
# Escaping Single Quote  
String1 = 'I\'m a "Geek"'
print("\nEscaping Single Quote: "
print(String1) 
    
# Escaping Doule Quotes 
String1 = "I'm a \"Geek\""
print("\nEscaping Double Quotes: "
print(String1) 
    
# Printing Paths with the  
# use of Escape Sequences 
String1 = "C:\\Python\\Geeks\\"
print("\nEscaping Backslashes: "
print(String1) 

chevron_right


Output:

Initial String with use of Triple Quotes: 
I'm a "Geek"

Escaping Single Quote: 
I'm a "Geek"

Escaping Double Quotes: 
I'm a "Geek"

Escaping Backslashes: 
C:\Python\Geeks\

Note – To know more about strings click here.

2) List

Lists are just like the arrays, declared in other languages. Lists need not be homogeneous always which makes it the most powerful tool in Python. A single list may contain DataTypes like Integers, Strings, as well as Objects. Lists are mutable, and hence, they can be altered even after their creation. List in Python are ordered and have a definite count. The elements in a list are indexed according to a definite sequence and the indexing of a list is done with 0 being the first index. Each element in the list has its definite place in the list, which allows duplicating of elements in the list, with each element having its own distinct place and credibility. It is represented by list class.

Creating a list


Lists in Python can be created by just placing the sequence inside the square brackets[]. Unlike Sets, list doesn’t need a built-in function for creation of list.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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 = ['GeeksForGeeks'
print("\nList with the use of String: "
print(List
    
# Creating a List with 
# the use of multiple values 
List = ["Geeks", "For", "Geeks"
print("\nList containing multiple values: "
print(List[0])  
print(List[2]) 
    
# Creating a Multi-Dimensional List 
# (By Nesting a list inside a List) 
List = [['Geeks', 'For'], ['Geeks']] 
print("\nMulti-Dimensional List: "
print(List

chevron_right


Output:

Intial blank List: 
[]

List with the use of String: 
['GeeksForGeeks']

List containing multiple values: 
Geeks
Geeks

Multi-Dimensional List: 
[['Geeks', 'For'], ['Geeks']]

Adding Elements to a List

Elements can be added to the List by using built-in append() function. Only one element at a time can be added to the list by using append() method. For addition of element at the desired position, insert() method is used. Other than append() and insert() methods, there’s one more method for Addition of elements, extend(), this method is used to add multiple elements at the same time at the end of the list.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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, 'Geeks'
print("\nList after performing Insert Operation: "
print(List
  
# Addition of multiple elements 
# to the List at the end 
# (using Extend Method) 
List.extend([8, 'Geeks', 'Always']) 
print("\nList after performing Extend Operation: "
print(List

chevron_right


Output:

Initial blank List: 
[]

List after Addition of Three elements: 
[1, 2, 4]

List after performing Insert Operation: 
['Geeks', 1, 2, 4, 12]

List after performing Extend Operation: 
['Geeks', 1, 2, 4, 12, 8, 'Geeks', 'Always']

Accessing elements from the List

In order to access the list items refer to the index number.Use the index operator [ ] to access an item in a list.The index must be an integer. Nested list is accessed using nested indexing. In Python, negative sequence indexes represent positions from the end of the array. Instead of having to compute the offset as in List[len(List)-3], it is enough to just write List[-3]. Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second last item etc.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to demonstrate  
# accessing of element from list 
    
# Creating a List with 
# the use of multiple values 
List = ["Geeks", "For", "Geeks"
    
# 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]) 

chevron_right


Output:

Accessing element from the list
Geeks
Geeks
Accessing element using negative indexing
Geeks
Geeks

Removing Elements from the List

Elements can be removed from the List by using built-in remove() function but an Error arises if element doesn’t exist in the set. Pop() function can also be used to remove and return an element from the set, but by default it removes only the last element of the set, to remove element from a specific position of the List, index of the element is passed as an argument to the pop() method.


Note – Remove method in List will only remove the first occurrence of the searched element.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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

chevron_right


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]

Note – To know more about list click here.

3) Tuple

Tuple is an ordered collection of Python objects much like a list. The sequence of values stored in a tuple can be of any type, and they are indexed by integers. The important difference between a list and a tuple is that tuples are immutable. Also, Tuples are hashable whereas lists are not. It is represented by tuple class.

Creating a Tuple

In Python, tuples are created by placing sequence of values separated by ‘comma’ with or without the use of parentheses for grouping of data sequence. Tuples can contain any number of elements and of any datatype (like strings, integers, list, etc.). Tuples can also be created with a single element, but it is a bit tricky. Having one element in the parentheses is not sufficient, there must be a trailing ‘comma’ to make it a tuple.

Note – Creation of Python tuple without the use of parentheses is known as Tuple Packing.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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 = ('Geeks', '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('Geeks'
print("\nTuple with the use of function: "
print(Tuple1) 
  
# Creating a Tuple  
# with nested tuples 
Tuple1 = (0, 1, 2, 3
Tuple2 = ('python', 'geek'
Tuple3 = (Tuple1, Tuple2) 
print("\nTuple with nested tuples: "
print(Tuple3) 

chevron_right


Output:

Initial empty Tuple: 
()

Tuple with the use of String: 
('Geeks', 'For')

Tuple using List: 
(1, 2, 4, 5, 6)

Tuple with the use of function: 
('G', 'e', 'e', 'k', 's')

Tuple with nested tuples: 
((0, 1, 2, 3), ('python', 'geek'))

Accessing element of a tuple

In order to access the tuple items refer to the index number. Use the index operator [ ] to access an item in a tuple. The index must be an integer. Nested tuple are accessed using nested indexing.


filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

Frist element of tuple
1

Last element of tuple
5

Third last element of tuple
3

Deleting/updating elements of tuple

In python, deletion or Updation of a tuple is not allowed. This will cause an error because updating or deleting from a tuple is not supported. This is because tuples are immutable, hence elements of a tuple cannot be changed once it has been assigned. Only new tuples can be reassigned to the same name.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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

Note – To know more about tuples click here.

Boolean

Data type with one of the two built-in values, True or False. Boolean objects that are equal to True are truthy (true), and those equal to False are falsy (false). But non-Boolean objects can be evaluated in Boolean context as well and determined to be true or false. It is denoted by the class bool.

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

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to 
# demonstrate boolean type
  
print(type(True))
print(type(False))
  
print(type(true))

chevron_right


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 iterable, mutable and has no duplicate elements. The order of elements in a set is undefined though it may consist of various elements. The major advantage of using a set, as opposed to a list, is that it has a highly optimized method for checking whether a specific element is contained in the set.

Creating a set

Sets can be created by using the built-in set() function with an iterable object or a sequence by placing the sequence inside curly braces, separated by ‘comma’. A set contains only unique elements but at the time of set creation, multiple duplicate values can also be passed. The order of elements in a set is undefined and is unchangeable. Type of elements in a set need not be the same, various mixed-up data type values can also be passed to the set.


filter_none

edit
close

play_arrow

link
brightness_4
code

# 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("GeeksForGeeks"
print("\nSet with the use of String: "
print(set1) 
  
# Creating a Set with 
# the use of a List 
set1 = set(["Geeks", "For", "Geeks"]) 
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, 'Geeks', 4, 'For', 6, 'Geeks']) 
print("\nSet with the use of Mixed Values"
print(set1) 

chevron_right


Output:

Intial blank Set: 
set()

Set with the use of String: 
{'F', 'o', 'G', 's', 'r', 'k', 'e'}

Set with the use of List: 
{'Geeks', 'For'}

Set with the use of Mixed Values
{1, 2, 4, 6, 'Geeks', 'For'}

Adding Elements to a Set

Elements can be added to the Set by using built-in add() function. Only one element at a time can be added to the set by using add() method. For addition of two or more elements Update() method is used.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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

Accessing a Set

Set items cannot be accessed by referring to an index, since sets are unordered the items has no index. But you can loop through the set items using a for loop, or ask if a specified value is present in a set, by using the in keyword.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to demonstrate 
# Accessing of elements in a set 
    
# Creating a set 
set1 = set(["Geeks", "For", "Geeks"]) 
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("Geeks" in set1) 

chevron_right


Output:

Initial set: 
{'Geeks', 'For'}

Elements of set: 
Geeks For 

True

Removing elements from a set

Elements can be removed from the Set by using built-in remove() function but a KeyError arises if element doesn’t exist in the set. To remove elements from a set without KeyError, use discard(). Pop() function can also be used to remove and return an element from the set, but it removes only the last element of the set. To remove all the elements from the set, clear() function is used.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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

Note – To know more about sets click here.

Dictionary

Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only single value as an element, Dictionary holds key:value pair. Key-value is provided in the dictionary to make it more optimized. Each key-value pair in a Dictionary is separated by a colon :, whereas each key is separated by a ‘comma’.

Creating a dictionary


In Python, a Dictionary can be created by placing a sequence of elements within curly {} braces, separated by ‘comma’. Dictionary holds a pair of values, one being the Key and the other corresponding pair element being its Key:value. Values in a dictionary can be of any datatype and can be duplicated, whereas keys can’t be repeated and must be immutable.

Dictionary can also be created by the built-in function dict(). An empty dictionary can be created by just placing to curly braces{}.

Note – Dictionary keys are case sensitive, same name but different cases of Key will be treated distinctly.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Creating an empty Dictionary 
Dict = {} 
print("Empty Dictionary: "
print(Dict
    
# Creating a Dictionary  
# with Integer Keys 
Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'
print("\nDictionary with the use of Integer Keys: "
print(Dict
    
# Creating a Dictionary  
# with Mixed keys 
Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]} 
print("\nDictionary with the use of Mixed Keys: "
print(Dict
    
# Creating a Dictionary 
# with dict() method 
Dict = dict({1: 'Geeks', 2: 'For', 3:'Geeks'}) 
print("\nDictionary with the use of dict(): "
print(Dict
    
# Creating a Dictionary 
# with each item as a Pair 
Dict = dict([(1, 'Geeks'), (2, 'For')]) 
print("\nDictionary with each item as a pair: "
print(Dict

chevron_right


Output:

Empty Dictionary: 
{}

Dictionary with the use of Integer Keys: 
{1: 'Geeks', 2: 'For', 3: 'Geeks'}

Dictionary with the use of Mixed Keys: 
{1: [1, 2, 3, 4], 'Name': 'Geeks'}

Dictionary with the use of dict(): 
{1: 'Geeks', 2: 'For', 3: 'Geeks'}

Dictionary with each item as a pair: 
{1: 'Geeks', 2: 'For'}

Adding elements to a Dictionary

In Python Dictionary, Addition of elements can be done in multiple ways. One value at a time can be added to a Dictionary by defining value along with the key e.g. Dict[Key] = ‘Value’. Updating an existing value in a Dictionary can be done by using the built-in update() method.

Note – While adding a value, if the key-value already exists, the value gets updated otherwise a new Key with the value is added to the Dictionary.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Creating an empty Dictionary 
Dict = {} 
print("Empty Dictionary: "
print(Dict
    
# Adding elements one at a time 
Dict[0] = 'Geeks'
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

chevron_right


Output:

Empty Dictionary: 
{}

Dictionary after adding 3 elements: 
{0: 'Geeks', 2: 'For', 3: 1}

Updated key value: 
{0: 'Geeks', 2: 'Welcome', 3: 1}

Accessing elements from a Dictionary

In order to access the items of a dictionary refer to its key name. Key can be used inside square brackets. There is also a method called get() that will also help in accessing the element from a dictionary.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to demonstrate   
# accesing a element from a Dictionary  
    
# Creating a Dictionary  
Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'
    
# 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)) 

chevron_right


Output:

Accessing a element using key:
For
Accessing a element using get:
Geeks

Removing Elements from Dictionary

In Python Dictionary, deletion of keys can be done by using the del keyword. Using del keyword, specific values from a dictionary as well as whole dictionary can be deleted. Other functions like pop() and popitem() can also be used for deleting specific values and arbitrary values from a Dictionary. All the items from a dictionary can be deleted at once by using clear() method.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Initial Dictionary 
Dict = { 5 : 'Welcome', 6 : 'To', 7 : 'Geeks'
        'A' : {1 : 'Geeks', 2 : 'For', 3 : 'Geeks'}, 
        'B' : {1 : 'Geeks', 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

chevron_right


Output:

Initial Dictionary: 
{'B': {1: 'Geeks', 2: 'Life'}, 'A': {1: 'Geeks', 2: 'For', 3: 'Geeks'},
 5: 'Welcome', 6: 'To', 7: 'Geeks'}

Deleting a specific key: 
{'B': {1: 'Geeks', 2: 'Life'}, 'A': {1: 'Geeks', 2: 'For', 3: 'Geeks'},
 5: 'Welcome', 7: 'Geeks'}

Popping specific element: 
{'B': {1: 'Geeks', 2: 'Life'}, 'A': {1: 'Geeks', 2: 'For', 3: 'Geeks'}, 7: 'Geeks'}

Pops an arbitrary key-value pair: 
{'A': {1: 'Geeks', 2: 'For', 3: 'Geeks'}, 7: 'Geeks'}

Deleting Entire Dictionary: 
{}


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : shubham_singh

Article Tags :

2


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.