0% found this document useful (0 votes)
9 views33 pages

Python Chapter9 Dictonary PDF

The document provides an overview of Python dictionaries, including their structure, how to access and update values, and methods such as len(), str(), type(), clear(), copy(), fromkeys(), and get(). It explains the uniqueness of keys, the mutability of values, and the error handling when accessing non-existent keys. Additionally, it includes examples demonstrating the usage of these dictionary methods.

Uploaded by

adarshhalse45
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views33 pages

Python Chapter9 Dictonary PDF

The document provides an overview of Python dictionaries, including their structure, how to access and update values, and methods such as len(), str(), type(), clear(), copy(), fromkeys(), and get(). It explains the uniqueness of keys, the mutability of values, and the error handling when accessing non-existent keys. Additionally, it includes examples demonstrating the usage of these dictionary methods.

Uploaded by

adarshhalse45
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

Placement Python-Dictionar y

Classes
YoganandSharma

Each key is separated from its value by a colon (:), the


Training > Project >+91-9928016573
items are separated by commas, and the whole thing

y
is enclosed in curly braces. An empty dictionary
Training by

d
without any items is written with just two curly
JMD Study Computer

braces, like this: {}.


tu
S
D
Keys are unique within a dictionary while values may

JM
not be. Accessing Values in Dictionary
To access dictionary elements, you can use the
familiar square brackets along with the key to obtain
its value.

Python Notes 1
MCA/ M.Tech/ B.Tech/ BCA Internship/ Industrial/ Live Project
Training by Training.
Project Training in Python, Android, PHP, ASP.NET, Machine Learning, SQL, JAVA,
YoganandSharma
Web Designing, Digital Marketing, SEO, SMO, C, C++. Call: 9649141215, www.jmdstudy.com
+91-9928016573

Output:

dict['Age']: 7
J
dict['Name']: Zara

M
D
Stu
print ("dict['Age']: ", dict['Age'])
Python-Dictionar y
Following is a simple example −

d
print ("dict['Name']: ", dict['Name'])
y

Python Notes
dict= {'Name': 'Zara', 'Age': 7, 'Class': 'First'}

2
Assistance Python-Dictionar y
Classes
YoganandSharma

If we attempt to access a data item with a key, which is


not part of the dictionary, we get an error as follows −
+91-9928016573

dict= {'Name': 'Zara', 'Age': 7, 'Class': 'First'}


y
Training by

print ("dict['Alice']: ", dict['Alice'])


d
JMD Study Computer
Live Project & 100%Job

Output:
tu
dict['Alice']:
S
D
Traceback(most recent call last):
File "test.py", line 4, in <module>

JM
print "dict['Alice']: ", dict['Alice'];
KeyError: 'Alice'
Updating Dictionary
You can update a dictionary by adding a new entry or a
key-value pair, modifying an existing entry, or deleting an
existing entry as shown below in the simple example −

Python Notes 3
Web Designing, Digital Marketing, SEO, SMO, C, C++. Call: 9649141215, www.jmdstudy.com
Python-Dictionar y
Project Training in Python, Android, PHP, ASP.NET, Machine Learning, SQL, JAVA,
YoganandSharma

dict= {'Name': 'Zara', 'Age': 7, 'Class': 'First'}


by Training.

dict['Age'] = 8; # update existing entry


+91-9928016573

dict['School'] = "DPS School"; # Add new entry


Live Project

y
Training

d
print ("dict['Age']: ", dict['Age'])
u
MCA/ M.Tech/ B.Tech/ BCA Internship/ Industrial/

Output:
St
print ("dict['School']: ", dict['School'])

dict['Age']: 8
D
JM
dict['School']: DPS School
Delete Dictionary Elements
You can either remove individual dictionary elements or clear
the entire contents of a dictionary. You can also delete entire
dictionary in a single operation.
To explicitly remove an entire dictionary, just use the del
statement. Following is a simple example −
Python Notes 4
Placement Python-Dictionar y
Classes
YoganandSharma

dict= {'Name': 'Zara', 'Age': 7, 'Class': 'First'}


Training > Project >+91-9928016573
del dict['Name']; # remove entry with key 'Name'

y
Training by

dict.clear(); # remove all entries in dict


d
JMD Study Computer

tu
del dict; # delete entire dictionary
print ("dict['Age']: ", dict['Age'])
S
print ("dict['School']: ", dict['School'])
Output: D
dict['Age']:
JM
Traceback(most recent call last):
File "test.py", line 8, in <module>
print "dict['Age']: ", dict['Age'];

Python Notes 5
Web Designing, Digital Marketing, SEO, SMO, C, C++. Call: 9649141215, www.jmdstudy.com
Python-Dictionar y
Project Training in Python, Android, PHP, ASP.NET, Machine Learning, SQL, JAVA,
YoganandSharma
by Training.

+91-9928016573

TypeError: 'type' object is unsubscriptable


Live Project

y
Properties of Dictionary Keys
Training

ud
MCA/ M.Tech/ B.Tech/ BCA Internship/ Industrial/

St
Dictionary values have no restrictions. They can be
any arbitrary Python object, either standard objects
D
or user-defined objects. However, same is not true
for the keys.
JM

Python Notes 6
Assistance Python-Dictionar y
Classes
YoganandSharma

dict= {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'}


+91-9928016573

print ("dict['Name']: ", dict['Name'])

y
Training by

Output:
d
JMD Study Computer
Live Project & 100%Job

dict['Name']: Manni
tu
S
(b) Keys must be immutable. Which means you can
D
use strings, numbers or tuples as dictionary keys but

JM
something like ['key'] is not allowed. Following is a
simple

Python Notes 7
Web Designing, Digital Marketing, SEO, SMO, C, C++. Call: 9649141215, www.jmdstudy.com
Python-Dictionar y-functions
Project Training in Python, Android, PHP, ASP.NET, Machine Learning, SQL, JAVA,
YoganandSharma

Description
by Training.

Python dictionary method len()gives the total length of the


+91-9928016573

dictionary. This would be equal to the number of items in the


Live Project

dictionary.
y
Training

ud
MCA/ M.Tech/ B.Tech/ BCA Internship/ Industrial/

Syntax
t
Following is the syntax for len() method −
S
len(dict)
D
Parameters

JM
dict−This is the dictionary, whose length needs to be
calculated.

Return Value
This method returns the length.

Python Notes 8
Placement Python-Dictionar y-functions
Classes
YoganandSharma

Example
Training > Project >+91-9928016573
The following example shows the usage of len()

y
Training by

method.
d
JMD Study Computer

tu
dict= {'Name': 'Zara', 'Age': 7};
S
print ("Length : " len(dict))
D
When we run above program, it produces following
result −
JM
Length : 2

Python Notes 9
Web Designing, Digital Marketing, SEO, SMO, C, C++. Call: 9649141215, www.jmdstudy.com
Python-Dictionar y-functions
Project Training in Python, Android, PHP, ASP.NET, Machine Learning, SQL, JAVA,
YoganandSharma

Description
by Training.

+91-9928016573

Python dictionary method str()produces a printable


Live Project

string representation of a dictionary.


y
Training

Syntax
ud
MCA/ M.Tech/ B.Tech/ BCA Internship/ Industrial/

t
Following is the syntax for str() method −
S
str(dict)
D
Parameters
JM
dict−This is the dictionary.

Return Value
This method returns string representation.

Python Notes 10
Assistance Python-Dictionar y-functions
Classes
YoganandSharma

Example
+91-9928016573

The following example shows the usage of str()

y
Training by

method.
d
JMD Study Computer
Live Project & 100%Job

tu
dict= {'Name': 'Zara', 'Age': 7};
S
print ("Equivalent String : " str(dict))
D
When we run above program, it produces following
result −
JM
Equivalent String : {'Age': 7, 'Name': 'Zara'}

Python Notes 11
Web Designing, Digital Marketing, SEO, SMO, C, C++. Call: 9649141215, www.jmdstudy.com
Python-Dictionar y-functions
Project Training in Python, Android, PHP, ASP.NET, Machine Learning, SQL, JAVA,
YoganandSharma

Description
by Training.

Python dictionary method type()returns the type of the


+91-9928016573

passed variable. If passed variable is dictionary then it


Live Project

would return a dictionary type.


y
Training

ud
MCA/ M.Tech/ B.Tech/ BCA Internship/ Industrial/

Syntax

St
Following is the syntax for type() method −

type(dict) D
Parameters
JM
dict−This is the dictionary.

Return Value
This method returns the type of the passed variable.

Python Notes 12
Placement Python-Dictionar y-functions
Classes
YoganandSharma

Example
Training > Project >+91-9928016573
The following example shows the usage of type()

y
Training by

method.
d
JMD Study Computer

dict= {'Name': 'Zara', 'Age': 7};


tu
print ("Variable Type : " type (dict))
S
When we run above program, it produces following
result
− D
JM
Variable Type : <type 'dict'>

Python Notes 13
MCA/ M.Tech/ B.Tech/ BCA Internship/ Industrial/ Live Project
Training by Training.
Project Training in Python, Android, PHP, ASP.NET, Machine Learning, SQL, JAVA,
Web Designing, Digital Marketing, SEO, SMO, C, C++. Call: 9649141215, www.jmdstudy.comYoganandSharma
+91-9928016573

NA
Syntax

dict.clear()
Description

Parameters

Return Value
JM
D
Study

This method does not return any value.

Python Notes
Following is the syntax for clear() method −
Python-Dictionar y-Methods
The method clear() removes all items from the dictionary.

14
Assistance Python-Dictionar y-Methods
Classes
YoganandSharma

Example
The following example shows the usage of clear()
+91-9928016573

method.
y
Training by

d
JMD Study Computer

dict= {'Name': 'Zara', 'Age': 7}


Live Project & 100%Job

tu
print ("Start Len : %d" % len(dict))

S
dict.clear()
D
print ("End Len : %d" % len(dict))
Result
Output: JM
Start Len : 2
End Len : 0

Python Notes 15
MCA/ M.Tech/ B.Tech/ BCA Internship/ Industrial/ Live Project
Training by Training.
Project Training in Python, Android, PHP, ASP.NET, Machine Learning, SQL, JAVA,
Web Designing, Digital Marketing, SEO, SMO, C, C++. Call: 9649141215, www.jmdstudy.com YoganandSharma
+91-9928016573

NA
Syntax
dictionary.

dict.copy()
Description

Parameters

Return Value
JM
D
Study

Python Notes
Following is the syntax for copy() method −
The method copy() returns a shallow copy of the
Python-Dictionar y-Methods

This method returns a shallow copy of the dictionary.

16
Placement Python-Dictionar y-Methods
Classes
YoganandSharma
Training > Project >+91-9928016573
Example

y
Training by

The following example shows the usage of copy() method.


d
JMD Study Computer

tu
dict1 = {'Name': 'Manni', 'Age': 7, 'Class': 'First'}
dict2 = dict1.copy() S
D
print ("New Dictionary : ",dict2)
Result
Output: JM
New dictionary : {'Name': 'Manni', 'Age': 7, 'Class': 'First'}

Python Notes 17
Web Designing, Digital Marketing, SEO, SMO, C, C++. Call: 9649141215, www.jmdstudy.com
Python-Dictionar y-Methods
Project Training in Python, Android, PHP, ASP.NET, Machine Learning, SQL, JAVA,
YoganandSharma

Description
by Training.

The method fromkeys() creates a new dictionary with keys


+91-9928016573

from seqand values set to value.


Live Project

y
Training

Syntax

ud
MCA/ M.Tech/ B.Tech/ BCA Internship/ Industrial/

Following is the syntax for fromkeys() method −


dict.fromkeys(seq[, value]))
St
Parameters
D
seq−This is the list of values which would be used for

JM
dictionary keys preparation.
value −This is optional, if provided then value would be set to
this value
Return Value
This method returns the list.

Python Notes 18
Assistance Python-Dictionar y-Methods
Classes
YoganandSharma

Example
The following example shows the usage of fromkeys()
+91-9928016573

method.
y
Training by

seq= ('name', 'age', 'sex')


d
JMD Study Computer
Live Project & 100%Job

dict= dict.fromkeys(seq)
tu
S
print ("New Dictionary : %s" % str(dict))

D
dict= dict.fromkeys(seq, 10)

JM
print ("New Dictionary : %s" % str(dict))
Result
Output:
New Dictionary : {'age': None, 'name': None, 'sex': None}
New Dictionary : {'age': 10, 'name': 10, 'sex': 10}

Python Notes 19
Web Designing, Digital Marketing, SEO, SMO, C, C++. Call: 9649141215, www.jmdstudy.com
Python-Dictionar y-Methods
Project Training in Python, Android, PHP, ASP.NET, Machine Learning, SQL, JAVA,
YoganandSharma

Description
by Training.

The method get() returns a value for the given key. If key is not
+91-9928016573

available then returns default value None.


Live Project

y
Training

Syntax

ud
MCA/ M.Tech/ B.Tech/ BCA Internship/ Industrial/

Following is the syntax for get() method −


dict.get(key, default=None)
St
Parameters
D
key −This is the Key to be searched in the dictionary.

JM
default −This is the Value to be returned in case key does not
exist.
Return Value
This method return a value for the given key. If key is not
available, then returns default value None.

Python Notes 20
Placement Python-Dictionar y-Methods
Classes
YoganandSharma

Example
Training > Project >+91-9928016573

The following example shows the usage of get() method.


y
Training by

d
JMD Study Computer

tu
dict= {'Name': 'Zara', 'Age': 27}
S
D
print ("Value : %s" % dict.get('Age'))

Result
Output: JM
print ("Value : %s" % dict.get('Sex', "NA"))

Value : 27
Value : NA

Python Notes 21
Web Designing, Digital Marketing, SEO, SMO, C, C++. Call: 9649141215, www.jmdstudy.com
Python-Dictionar y-Methods
Project Training in Python, Android, PHP, ASP.NET, Machine Learning, SQL, JAVA,
YoganandSharma

Description
by Training.

+91-9928016573

The method has_key() returns true if a given key is


Live Project

available in the dictionary, otherwise it returns a false.


y
Training

Syntax
ud
MCA/ M.Tech/ B.Tech/ BCA Internship/ Industrial/

dict.has_key(key) St
Following is the syntax for has_key() method −

Parameters D
JM
key −This is the Key to be searched in the dictionary.

Return Value
This method return true if a given key is available in the
dictionary, otherwise it returns a false.

Python Notes 22
Assistance Python-Dictionar y-Methods
Classes
YoganandSharma

Example
+91-9928016573

The following example shows the usage of has_key()


method.
y
Training by

d
dict= {'Name': 'Zara', 'Age': 7}
JMD Study Computer
Live Project & 100%Job

tu
print ("Value : %s" % dict.has_key('Age'))
S
print ("Value : %s" % dict.has_key('Sex'))
D
When we run the above program, it produces the

JM
following result −

Value : True
Value : False

Python Notes 23
MCA/ M.Tech/ B.Tech/ BCA Internship/ Industrial/ Live Project
Training by Training.
Project Training in Python, Android, PHP, ASP.NET, Machine Learning, SQL, JAVA,
Web Designing, Digital Marketing, SEO, SMO, C, C++. Call: 9649141215, www.jmdstudy.com YoganandSharma
+91-9928016573

NA
Syntax
tuple pairs
Description

dict.items()
Parameters

Return Value
JM
D
Study

This method returns a list of tuple pairs.

Python Notes
Following is the syntax for items() method −
Python-Dictionar y-Methods
The method items() returns a list of dict's(key, value)

24
Placement Python-Dictionar y-Methods
Classes
YoganandSharma

Example
Training > Project >+91-9928016573
The following example shows the usage of items()

y
Training by

method.
d
JMD Study Computer

dict= {'Name': 'Zara', 'Age': 7}


tu
print ("Value : %s" % dict.items())
Output: S
D
JM
Value : [('Age', 7), ('Name', 'Zara')]

Python Notes 25
Web Designing, Digital Marketing, SEO, SMO, C, C++. Call: 9649141215, www.jmdstudy.com
Python-Dictionar y-Methods
Project Training in Python, Android, PHP, ASP.NET, Machine Learning, SQL, JAVA,
YoganandSharma

Description
by Training.

The method keys() returns a list of all the available keys in


+91-9928016573

the dictionary.
Live Project

y
Training

Syntax
ud
MCA/ M.Tech/ B.Tech/ BCA Internship/ Industrial/

t
Following is the syntax for keys() method −

S
dict.keys()
Parameter D
s NA
JM
Return Value
This method returns a list of all the available keys in the
dictionary.

Python Notes 26
Assistance Python-Dictionar y-Methods
Classes
YoganandSharma

.
+91-9928016573

Example

y
Training by

The following example shows the usage of keys() method.


d
JMD Study Computer
Live Project & 100%Job

Live Demo
tu
#!/usr/bin/python3
S
D
dict= {'Name': 'Zara', 'Age': 7}

JM
print ("Value : %s" % dict.keys())
Result
When we run above program, it produces the following result

Value : dict_keys(['Age', 'Name'])

Python Notes 27
Placement Python-Dictionar y-Methods
Classes
YoganandSharma

Description
The method setdefault() is similar to get(), but will set
Training > Project >+91-9928016573
dict[key] = default if key is not already in dict.
y
Training by

Syntax
d
JMD Study Computer

tu
Following is the syntax for setdefault() method −

S
dict.setdefault(key, default = None)
Parameters
D
key −This is the key to be searched.

JM
default −This is the Value to be returned in case key is
not found.
Return Value
This method returns the key value available in the
dictionary and if given key is not available then it will
return provided default value.

Python Notes 28
Web Designing, Digital Marketing, SEO, SMO, C, C++. Call: 9649141215, www.jmdstudy.com
Python-Dictionar y-Methods
Project Training in Python, Android, PHP, ASP.NET, Machine Learning, SQL, JAVA,
YoganandSharma

.Example
by Training.

+91-9928016573

The following example shows the usage of setdefault()


Live Project

method.
y
Training

ud
dict= {'Name': 'Zara', 'Age': 7}
print ("Value : %s" % dict.setdefault('Age', None))
MCA/ M.Tech/ B.Tech/ BCA Internship/ Industrial/

print (dict) St
print ("Value : %s" % dict.setdefault('Sex', None))

Result D
Output:
JM
Value : 7
Value : None
{'Name': 'Zara', 'Sex': None, 'Age': 7}

Python Notes 29
Assistance Python-Dictionar y-Methods
Classes
YoganandSharma

Description
+91-9928016573

The method update() adds dictionary dict2's key-values


pairs in to dict. This function does not return anything.
y
Training by

d
JMD Study Computer
Live Project & 100%Job

Syntax
tu
Following is the syntax for update() method −
S
D
dict.update(dict2)
Parameters
JM
dict2 −This is the dictionary to be added into dict.

Return Value
This method does not return any value.

Python Notes 30
Placement Python-Dictionar y-Methods
Classes
YoganandSharma

Example
Training > Project >+91-9928016573
The following example shows the usage of update()
method.
y
Training by

d
dict= {'Name': 'Zara', 'Age': 7}
JMD Study Computer

dict2 = {'Sex': 'female' }


tu
dict.update(dict2) S
D
print ("updated dict: ", dict)
Result
JM
When we run above program, it produces the following

result

updated dict: {'Sex': 'female', 'Age': 7, 'Name': 'Zara'}

Python Notes 31
Web Designing, Digital Marketing, SEO, SMO, C, C++. Call: 9649141215, www.jmdstudy.com
Python-Dictionar y-Methods
Project Training in Python, Android, PHP, ASP.NET, Machine Learning, SQL, JAVA,
YoganandSharma

Description
by Training.

The method values() returns a list of all the values


+91-9928016573

available in a given dictionary.


Live Project

y
Training

Syntax
ud
MCA/ M.Tech/ B.Tech/ BCA Internship/ Industrial/

t
Following is the syntax for values() method −

S
dict.values()
Parameter D
s NA
JM
Return Value
This method returns a list of all the values available in a
given dictionary.

Python Notes 32
Assistance Python-Dictionar y-Methods
Classes
YoganandSharma
+91-9928016573

Exampl

y
Training by

The following example shows the usage of values()


d
JMD Study Computer

e
Live Project & 100%Job

tu
method.
S
D
dict= {'Sex': 'female', 'Age': 7, 'Name': 'Zara'}

Result JM
print ("Values : ", list(dict.values()))

Output:

Values : ['female', 7, 'Zara']

Python Notes 33

You might also like