0% found this document useful (0 votes)
21 views

Python Module 2

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Python Module 2

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 76

Programming

in Python


Module 2 COMPOUND DATA
TYPES: STRINGS, LISTS,
TUPLES - declaration, Built
in functions.
DICTIONARIES: Concept
of dictionary, techniques to
create, update & delete
dictionary items. .
Strings are amongst the most popular types in python.

Python We can create them simply by enclosing characters in quotes.

strings
Python treats single quotes the same as double quotes.

Creating strings is as simple as assigning a value to a variable.

For example −

var1 = ‘Hello World!‘


Var2 = “Python Programming“
Accessing Values in Strings
• Python does not support a character type; these are treated as strings of length one, thus
also considered a substring.

• To access substrings, use the square brackets for slicing along with the index or indices to
obtain a substring.

For example −

var1 = ‘Hello World!‘

var2 = “Python Programming“

print ("var1[0]: ", var1[0])

print ("var2[1:5]: ", var2[1:5])

When the above code is executed, it produces the following result −

var1[0]: H

var2[1:5]: ytho
Updating Strings

• We can "update" an existing string by (re)assigning a variable to another string.


• The new value can be related to its previous value or to a completely different
string altogether.

For example −
var1 = 'Hello World!‘
print ("Updated String :- ", var1[:6] + 'Python')

When the above code is executed, it produces the


following result −
Updated String :- Hello Python
String
Special
Operators

Assume string
variable a holds 'Hello'
and variable b holds
'Python', then −
String Formatting Operator

• One of Python's coolest features is the string format operator %.


• This operator is unique to strings and makes up for the pack of having
functions from C's printf() family.
Following is a simple example −

print ("My name is %s and weight is %d kg!" % ('Zara', 21))

When the above code is executed, it produces the


following result −
My name is Zara and weight is 21 kg!
Here is the list of complete set of symbols which can be used along with %
Triple Quotes
• Python's triple quotes comes to the rescue by allowing strings to span multiple lines, including verbatim
NEWLINEs, TABs, and any other special characters.

• The syntax for triple quotes consists of three consecutive single or double quotes.

For example—

para_str = “””this is a long string that is made up of

several lines and non-printable characters such as

TAB ( \t ) and they will show up that way when displayed.

NEWLINEs within the string, whether explicitly given like

this within the brackets [ \n ], or just a NEWLINE with in

the variable assignment will also show up.

”””

print (para_str)

When the above code is executed, it produces the following result:-


OUTPUT:-
this is a long string that is made up of
several lines and non-printable characters such as
TAB ( ) and they will show up that way when displayed.
NEWLINEs within the string, whether explicitly given like
this within the brackets [
], or just a NEWLINE with in
the variable assignment will also show up.

* Note how every single special character has been converted to its printed form,
right down to the last NEWLINE at the end of the string between the "up." and closing
triple quotes. Also note that NEWLINEs occur either with an explicit carriage return at
the end of a line or its escape code (\n) −
Unicode String

• Normal strings in Python are stored internally as 8-bit ASCII, while Unicode strings are stored as 16-
bit Unicode.
• This allows for a more varied set of characters, including special characters from most languages in
the world.

For example--
print u'Hello, world!'
--When the above code is executed, it produces the
following result −
Hello, world!

Unicode strings use the prefix u, just as raw strings use


the prefix r.
Built-in String Methods
Python includes the following built-in methods to manipulate strings :-
1. capitalize():- Capitalizes first letter of string
Syntax
str.capitalize()
Example
Str="this is python programming"
print ("str.capitalize():",str.capitalize(Str))

2. Center(width, fillchar):- Returns a space-padded string with the original string centered to a
total of width columns.
Syntax
str.center(width[, fillchar])
Example
str = "this is string example....wow!!!"
print ("str.center(40, 'a') : ", str.center(40, 'a'))
3. count(beg = 0, end = len(string)):- Counts how many times str occurs in
string or in a substring of string if starting index beg and ending index end
are given.
Syntax
str.count(sub, start= 0,end=len(string))
example
str = "this is string example....wow!!!"
sub = 'i'
print ("str.count('i') : ", str.count(sub))
sub = 'exam'
print ("str.count('exam', 10, 40) : ", str.count(sub,10,40))

4. find(str, beg = 0,end = len(string)):- Determine if str occurs in string or in


a substring of string if starting index beg and ending index end are given
returns index if found and -1 otherwise.
Syntax
str.find(str, beg=0, end=len(string))
example
str1 = "this is string example....wow!!!"
str2 = "exam"
print (str1.find(str2))
print (str1.find(str2, 10))
print (str1.find(str2, 40))
5. index(str, beg = 0, end = len(string)):- Same as find, but raises an
exception if str not found.
Syntax
str.index(str, beg=0,end=len(string))
example
str1 = "this is string example....wow!!!"
str2 = "exam"
print (str1.index(str2))
print (str1.index(str2, 10))
print (str1.index(str2, 40))
6. isalnum() :- Returns true if string has at least 1 character and all
characters are alphanumeric and false otherwise.
Syntax
str.isalnum()
example
str = "this2016" # No space in this string
print (str.isalnum())

str = "this is string example....wow!!!"


print (str.isalnum())
7. isalpha():Returns true if string has at least 1 character and all
characters are alphabetic and false otherwise.
Syntax
str.isalpha()

example
str = "this“ # No space & digit in this string
print (str.isalpha())
str = "this is string example....wow!!!"
print (str.isalpha())
8. isdigit():- Returns true if string contains only digits and false
otherwise.
Syntax
str.isdigit()

example
str = "123456“ # Only digit in this string
print (str.isdigit())
str = "this is string example....wow!!!"
print (str.isdigit())
9. islower() :-Returns true if string has at least 1 cased character and all
cased characters are in lowercase and false otherwise.
Syntax
str.islower()
example
str = "THIS is string example....wow!!!"
print (str.islower())
str = "this is string example....wow!!!"
print (str.islower())

10. isnumeric():- Returns true if a unicode string contains only numeric


characters and false otherwise.
Syntax
str.isnumeric()
example
str = u"this2009"
print (str.isnumeric())
str = u"23443434"
print (str.isnumeric())
11.isspace():- Returns true if string contains only whitespace characters
and false otherwise.
Syntax
str.isspace()

example str = " "


print (str.isspace())
str = "This is string example....wow!!!"
print (str.isspace())

12.istitle():- Returns true if string is properly "titlecased" and false


otherwise.
Syntax
str.istitle()

example
str = "This Is String Example...Wow!!!
print (str.istitle())
str = "This is string example....wow!!!"
print (str.istitle())
13. isupper():-Returns true if string has at least one cased character and
all cased characters are in uppercase and false otherwise.
Syntax
str.isupper()
example
str = "THIS IS STRING EXAMPLE....WOW!!!"
print (str.isupper())
str = "THIS is string example....wow!!!"
print (str.isupper())
14. join(seq):- Merges (concatenates) the string representations of
elements in sequence seq into a string, with separator string.
Syntax
str.join(sequence)
example
s = "-"
seq = ("a", "b", "c") # This is sequence of strings.
print (s.join( seq ))
15. len(string):- Returns the length of the string
Syntax
len( str )

example
str = "this is string example....wow!!!"
print ("Length of the string: ", len(str))

16. ljust(width[, fillchar]):- Returns a space-padded string with the


original string left-justified to a total of width columns.
Syntax
str.ljust(width[, fillchar])

example
str = "this is string example....wow!!!"
print str.ljust(50, '0')
17. lower():- Converts all uppercase letters in string to lowercase.
Syntax
str.lower()

example
str = "THIS IS STRING EXAMPLE....WOW!!!"
print str.lower()

18.lstrip():- Removes all leading whitespace in string.


Syntax
str.lstrip([chars])

example
str = " this is string example....wow!!! "
print str.lstrip()
str = "88888888this is string example....wow!!!8888888"
print (str.lstrip('8’))
19. max(str):- Returns the max alphabetical character from the string
str.
Syntax
max(str)

example
str = "this is really a string example....wow!!!"
print "Max character: " + max(str)
str = "this is a string example....wow!!!"
print "Max character: " + max(str)

20. min(str):- Returns the min alphabetical character from the string str.
Syntax
min(str)

example
str = "www.google.com"
print ("Min character: " + min(str))
str = "GOOGLE"
print ("Min character: " + min(str))
21. replace(old, new [, max]):- Replaces all occurrences of old in string with
new or at most max occurrences if max given.
Syntax
str.replace(old, new[, max])
example
str = "this is string example....wow!!! this is really string"
print (str.replace("is", "was"))
print (str.replace("is", "was", 2))

22. rfind(str, beg=0,end=len(string)):- Same as find(), but search backwards


in string.
Syntax
str.rfind(str, beg=0 end=len(string))
example
str1 = "this is really a string example....wow!!!"
str2 = "is"
print (str1.rfind(str2))
print (str1.rfind(str2, 0, 10))
print (str1.rfind(str2, 10))
23. rindex( str, beg=0, end=len(string)):- Same as index(), but search
backwards in string.
Syntax
str.rindex(str, beg=0 end=len(string))

example
str1 = "this is string example....wow!!!"
str2 = "is"
print (str1.rindex(str2))
print (str1.index(str2))

24. rjust(width,[, fillchar]):- Returns a space-padded string with the


original string right-justified to a total of width columns.
Syntax
str.rjust(width[, fillchar])

example
str = "this is string example....wow!!!"
print str.rjust(50, '0')
25. rstrip():- Removes all trailing whitespace of string.
Syntax
str.rstrip([chars])
example
str = " this is string example....wow!!! "
print (str.rstrip())
str = "88888888this is string example....wow!!!8888888"
print (str.rstrip('8’))

26. split(str="", num=string.count(str)):- Splits string according to delimiter


str (space if not provided) and returns list of substrings; split into at most
num substrings if given.
Syntax
str.split(str="", num=string.count(str))
example
str = "this is string example....wow!!!“
print (str.split( ))
print (str.split('i',1))
print (str.split('w'))
27. splitlines( num=string.count('\n')):- Splits string at all (or num)
NEWLINEs and returns a list of each line with NEWLINEs removed.
Syntax
str.splitlines( num = string.count('\n’))

example
str = "this is \nstring example....\nwow!!!"
print (str.splitlines( ))

28.startswith(str, beg=0,end=len(string)):- Determines if string or a


substring of string (if starting index beg and ending index end are given)
starts with substring str; returns true if so and false otherwise.
Syntax
str.startswith(str, beg=0,end=len(string))

example
str = "this is string example....wow!!!"
print str.startswith( 'this' )
print str.startswith( 'is', 2, 4 )
print str.startswith( 'this', 2, 4 )
29. strip([chars]):- Performs both lstrip() and rstrip() on string
Syntax
str.strip([chars])

example
str = "0000000this is string example....wow!!!0000000"
print (str.strip( '0’ ))

30. swapcase():- Inverts case for all letters in string.


Syntax
str.swapcase()

example
str = "this is string example....wow!!!"
print (str.swapcase())
str = "THIS IS STRING EXAMPLE....WOW!!!"
print (str.swapcase())
31. title():- Returns "titlecased" version of string, that is, all words begin
with uppercase and the rest are lowercase.
Syntax
str.title()

example
str = "this is string example....wow!!!"
print (str.title())

32. upper():- Converts lowercase letters in string to uppercase.


Syntax
str.upper()

example
str = "this is string example....wow!!!"
print ("str.capitalize() : ", str.upper())
33. zfill (width):- Returns original string left padded with zeros to a total
of width characters;
Syntax
str.zfill(width)
example
str = "this is string example....wow!!!"
print (str.zfill(40))
print (str.zfill(50))

34.isdecimal():- Returns true if a unicode string contains only decimal


characters and false otherwise.
Syntax
str.isdecimal()
example
str = u"this2009"
print (str.isdecimal())
str = u"23443434"
print (str.isdecimal())
Python Lists
1. Lists are Mutable ordered sequence of items of mixed types.

2. We can Define lists using square brackets and commas.


For example
>>> li = [“abc”, 34, 4.34, 23]

3. We can Access individual members of a list using square bracket “array”


notation.
For example
>>> li = [“abc”, 34, 4.34, 23]
>>> li[1] # Second item in the list.
34
Lists are mutable
>>> li = [‘abc’, 23, 4.34, 23]
>>> li[1] = 45
>>> li
[‘abc’, 45, 4.34, 23]

We can change lists in place.


Name li still points to the same memory reference when we’re done.
Operations on lists

Membership operation
>>> 3 in [1, 2, 3]
True
Iteration operation
>>>for x in [1,2,3]:
print x
1
2
3
Length of the list
>>>len([1, 2, 3])
3
The + Operator
The + operator produces a new list whose
value is the concatenation of its arguments.
>>> [1, 2, 3] + [4, 5, 6]
[1, 2, 3, 4, 5, 6]
The * Operator
The * operator produces a new list that
“repeats” the original content.
>>> [1, 2, 3] * 3
1, 2, 3, 1, 2, 3, 1, 2, 3]
Deleting List Elements
To remove a list element, we can use either the del statement if we know
exactly which element(s) we are deleting or the remove() method if we do
not know.
For example −
Using del statement----uses index value
>>> list = ['physics', 'chemistry', 1997, 2000]
>>> del list[2]
>>> print list
['physics', 'chemistry', 2000]
using remove()----element as parameter
>>> list = ['physics', 'chemistry', 1997, 2000]
>>> list.remove(2000)
>>> print list
['physics', 'chemistry', 1997]
Accessing list elements

L = ['spam', 'Spam', 'SPAM!']


>>>L[2] #Offsets start at zero
‘SPAM’

>>>L[-2] #Negative: count from the right


‘Spam’

>>>L[1:2]
'Spam‘ #Slicing fetches sections

>>>L[0:]
'spam', 'Spam', 'SPAM!'
Methods
>>> li = [1, 11, 3, 4, 5]

>>> li.append(‘a’) # Note the method syntax


>>> li
[1, 11, 3, 4, 5, ‘a’]

>>> li.insert(2, ‘i’)


>>>li
[1, 11, ‘i’, 3, 4, 5, ‘a’]
The extend method vs +
+ creates a fresh list with a new memory ref
extend operates on list li in place.
>>> li.extend([9, 8, 7])
>>> li
[1, 2, ‘i’, 3, 4, 5, ‘a’, 9, 8, 7]

Potentially confusing:
◦ extend takes a list as an argument.
◦ append takes a singleton as an argument.
>>> li.append([10, 11, 12])
>>> li
[1, 2, ‘i’, 3, 4, 5, ‘a’, 9, 8, 7, [10, 11, 12]]
Lists have many methods, including index, count, remove, reverse, sort
>>> li = [‘a’, ‘b’, ‘c’, ‘b’]
>>> li.index(‘b’) # index of 1st occurrence
1
>>> li.count(‘b’) # number of occurrences
2
>>> li.remove(‘b’) # remove 1st occurrence
>>> li
[‘a’, ‘c’, ‘b’]
>>> li = [5, 2, 6, 8]

>>> li.reverse() # reverse the list *in place*


>>> li
[8, 6, 2, 5]

>>> li.sort() # sort the list *in place*


>>> li
[2, 5, 6, 8]

>>> li.sort(some_function)
# sort in place using user-defined comparison
>>> li = [5, 2, 6, 8]

insert(i,x)
>>> li.insert(3,4)

>>> li
[5,2,6,4,8]

remove(x)
>>> li.remove(6)
>>> li
[5,2,4,8]

pop([i]), pop()
>>> li.pop(3)
>>>li
[5,2,6,8]
max(list) Returns item from the list with max value.
>>> li=[1,56,72,'a']
>>> max(li)
'a‘

min(list) Returns item from the list with min value.


>>> li=[1,56,72,'a']
>>> min(li)
1

list(seq) Converts a tuple into list.


aTuple = (123, 'xyz', 'zara', 'abc')
aList = list(aTuple)
print ("List elements : ", aList)
List cmp() method compares elements of two lists.

Syntax
cmp(list1, list2)

Parameters
list1 − This is the first list to be compared.
list2 − This is the second list to be compared.

Return Value
1 if list1 is bigger than list2
-1 if list2 is bigger than list1
0 if both lists are equal
Python Tuples
1. A tuple is a sequence of immutable Python objects.
2. Tuples are sequences, just like lists.
3. The differences between tuples and lists are,tuples cannot be changed unlike
lists. Tuples use parentheses, whereas lists use square brackets.
4. Creating a tuple is as simple as putting different comma-separated values.
5. Optionally we can put these comma-separated values between parentheses
also.

For example −
tup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5 )
tup3 = "a", "b", "c", "d"
The empty tuple is wri en as two parentheses containing nothing −
tup1 = ()
To write a tuple containing a single value we have to include a comma,
even though there is only one value −
tup1 = (50,)

Like string indices, tuple indices start at 0, and they can be sliced,
concatenated, and so on.
Accessing Values in Tuples:
To access values in tuple, use the square brackets for slicing along with
the index or indices to obtain value available at that index.

For example −
>>>tup1 = ('physics', 'chemistry', 1997, 2000)
>>>tup2 = (1, 2, 3, 4, 5, 6, 7 )
>>>print ("tup1[0]: ", tup1[0])
tup1[0]: physics
>>>print ("tup2[1:5]: ", tup2[1:5])
>>>tup2[1:5]
(2, 3, 4, 5)
Updating Tuples
Tuples are immutable.
which means we cannot update or change the values of tuple elements.
We can take portions of existing tuples to create new tuples as the following
example demonstrates −
>>>tup1 = (12, 34.56)
>>>tup2 = ('abc', 'xyz')
>>> tup1[1]='a'
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
tup1[1]='a'
TypeError: 'tuple' object does not support item assignment
>>>tup3 = tup1 + tup2
>>>print (tup3)
(12, 34.56, 'abc', 'xyz')
Deleting Tuple Elements
Removing individual tuple elements is not possible.
To explicitly remove an entire tuple, just use
the del statement.
For example:
>>>tup = ('physics', 'chemistry', 1997, 2000)
>>>print (tup)
('physics', 'chemistry', 1997, 2000)
>>>del tup
>>>print ("After deleting tup : "),print (tup)

After deleting tup :Traceback (most recent call last):File


"main.py", line 8, inprint (tup)NameError: name 'tup' is not
defined

Note an exception raised, this is because after del tup tuple does
not exist any more −
Basic Tuples Operations

Tuples respond to the + and * operators much like strings; they mean concatenation
and repetition here too, except that the result is a new tuple, not a string.

Operations on tuples
Indexing, Slicing, and Matrixes
Because tuples are sequences, indexing and slicing work the same way
for tuples as they do for strings.

Assuming following input −


T=('C++', 'Java', 'Python')

No Enclosing Delimiters
Any set of multiple objects, comma-separated, written without identifying
symbols, i.e., brackets for lists, parentheses for tuples, etc., default to tuples
>>> li='a','c'
>>> type(li)
<class 'tuple'>
Built-in Tuple Functions

Exists in version 2.0


cmp(tuple1, tuple2):- Compares elements of both tuples.
For example
>>>tuple1, tuple2 = (123, 'xyz'), (456, 'abc')
>>>print cmp(tuple1, tuple2)
-1
>>>print cmp(tuple2, tuple1)
1
>>>tuple3 = tuple2 + (786,);
>>>print cmp(tuple2, tuple3)
-1
len(tuple):- Gives the total length of the tuple.
For example
>>>tuple1, tuple2 = (123, 'xyz', 'zara'), (456, 'abc')
>>>print ("First tuple length : ", len(tuple1))
First tuple length : 3
>>>print ("Second tuple length : ", len(tuple2))
Second tuple length : 2
max(tuple):- Returns item from the tuple with max value.
For example
>>>tuple1, tuple2 = ('maths', 'che', 'phy', 'bio'), (456, 700, 200)
>>>print ("Max value element : ", max(tuple1))
Max value element : phy
>>>print ("Max value element : ", max(tuple2))
Max value element : 700
min(tuple):- Returns item from the tuple with min value.
For example
>>>tuple1, tuple2 = ('maths', 'che', 'phy', 'bio'), (456, 700, 200)
>>>print ("min value element : ", min(tuple1))
min value element : bio
>>>print ("min value element : ", min(tuple2))
min value element : 200

tuple(seq):- Converts a list into tuple.


For example
>>>list1= ['maths', 'che', 'phy', 'bio']
>>>tuple1=tuple(list1)
>>>print ("tuple elements : ", tuple1)
tuple elements : ('maths', 'che', 'phy', 'bio')
Python Dictionaries
1. Python's dictionaries are kind of hash table type.

2. A dictionary key can be almost any Python type, but are usually numbers or strings.

3. Values, on the other hand, can be any arbitrary Python object.

4. Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square braces ([]).

For example −

>>>dict = {}

>>>dict['one'] = "This is one"

>>>dict[2] = "This is two"

>>>dict1 = {'name': 'john','code':6734, 'dept': 'sales'}

>>>print (dict)

{'one': 'This is one’, 2: 'This is two’ }

>>>print (dict1) # Prints complete dictionary

{'name': 'john', 'code': 6734, 'dept': 'sales'}


Python dictionary

5. Dictionaries have no concept of order among elements.


6. It is incorrect to say that the elements are "out of order"; they are
simply unordered.
7. Each key is separated from its value by a colon (:), the items are
separated by commas, and the whole thing is enclosed in curly
braces.
8. An empty dictionary without any items is written with just two curly
braces, like this: {}.
9. Keys are unique within a dictionary while values may not be.
10. The values of a dictionary can be of any type, but the keys must be
of an immutable data type such as strings, numbers, or tuples.
Accessing Values in Dictionary:

• To access dictionary elements, we can use the familiar square


brackets along with the key to obtain its value.

For example −
>>>dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
>>>print ("dict['Name']: ", dict['Name'])
dict['Name']: Zara
>>>print ("dict['Age']: ", dict['Age'])
dict['Age']: 7
If we attempt to access a data item with a key, which is not part of the
dictionary it raises an error
For example—

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


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

When the above code is executed, it produces the following result −

dict['Alice']:Traceback (most recent call last):


File "test.py", line 4, in <module>
print ("dict['Alice']: ", dict['Alice']);
KeyError: 'Alice'
Updating Dictionary
• We can update a dictionary by adding a new entry i.e a key-value pair
• Modify an existing entry or
• Delete an existing entry

For example--
>>>dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
>>>dict['Age'] = 8 # Update existing entry
>>>dict['School'] = "DPS School" # Add new entry
>>>print ("dict['Age']: ", dict['Age'])
dict['Age']: 8
>>>print ("dict['School']: ", dict['School'])
dict['School']: DPS School
Delete Dictionary Elements
• We can either remove individual dictionary elements

• or clear the entire contents of a dictionary.

• We can also delete entire dictionary in a single operation.

• To explicitly remove an entire dictionary, just use the del statement.

For example −

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

>>>del dict['Name'] # remove entry with key 'Name’

>>> print (dict)

{'Age': 7, 'Class': 'First'}

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

>>> print (dict)

{}

>>>del dict # delete entire dictionary


>>> print ("dict['Age']: ", dict['Age'])

dict['Age']:

Traceback (most recent call last):


File "<pyshell#7>", line 1, in <module>
print ("dict['Age']: ", dict['Age'])
TypeError: 'type' object has no attribute '__getitem__'

Note:-an exception is raised because, after del dict, dictionary does not exist any more −
Properties of Dictionary Keys
• Dictionary values have no restrictions.
• They can be any arbitrary Python object, either standard objects or user-defined objects.
• Same is not true for the keys.

There are two important points to remember about dictionary keys −

(a) More than one entry per key is not allowed. Which means no duplicate key is allowed. When
duplicate keys are encountered during assignment, the last assignment wins.
For example--
>>>dict = {'Name': 'Zara', 'Age': 7, 'Name': ‘Anna'}
>>>print ("dict['Name']: ", dict['Name'])
dict['Name']: Anna
(b) Keys must be immutable. Which means you can use strings, numbers
or tuples as dictionary keys but something like ['key'] is not allowed.

For example--
>>>dict = {['Name']: 'Zara', 'Age': 7}
>>>print ("dict['Name']: ", dict['Name'])

When the above code is executed, it produces the


following result −
Trace back (most recent call last):
File "test.py", line 3, in <module>
dict = {['Name']: 'Zara', 'Age': 7};
Type Error: list objects are un hashable
Built-in Dictionary Functions & Methods
Python includes the following dictionary functions and methods –

1. Python dictionary cmp() Method :- The method cmp() compares two dictionaries based on key and values.

Syntax
cmp(dict1, dict2)

Parameters
dict1 -- This is the first dictionary to be compared with dict2.
dict2 -- This is the second dictionary to be compared with dict1.

Return Value
This method returns 0 if both dictionaries are equal,
-1 if dict1 < dict2 and
1 if dict1 > dict2.
For Example
>>>dict1 = {'Name': 'Zara', 'Age': 7}
>>>dict2 = {'Name': 'Mahnaz', 'Age': 27}
>>>dict3 = {'Name': 'Abid', 'Age': 27}
>>>dict4 = {'Name': 'Zara', 'Age': 7}
>>>print ("Return Value : %d" % cmp (dict1, dict2))
Return Value : -1
>>>print ("Return Value : %d" % cmp (dict2, dict3))
Return Value : 1
>>>print ("Return Value : %d" % cmp (dict1, dict4))
Return Value : 0
2. Python dictionary len() Method :- The method len() gives the total length of the
dictionary. This would be equal to the number of items in the dictionary.

Syntax
len(dict)

Parameters
dict -- This is the dictionary, whose length needs to be calculated.

Return Value
This method returns the length.

For Example--
>>>dict = {'Name': 'Zara', 'Age': 7}
>>>print ("Length : %d" % len (dict))
Length : 2
3. Python dictionary str() Method :- The method str() produces a printable string
representation of a dictionary.

Syntax
str(dict)

Parameters
dict -- This is the dictionary.

Return Value
This method returns string representation.

Example
>>>dict = {'Name': 'Zara', 'Age': 7}
>>>print ("Equivalent String : %s" % str (dict))
Equivalent String : {'Age': 7, 'Name': 'Zara'}
4. Python dictionary type() Method :- The method type() returns the type of the
passed variable. If passed variable is dictionary then it would return a dictionary
type.

Syntax
type(dict)

Parameters
dict -- This is the dictionary.

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

For Example
>>>dict = {'Name': 'Zara', 'Age': 7}
>>>print ("Variable Type : %s" % type (dict))
Variable Type : <type 'dict'>
5. Python dictionary clear() Method :- The method clear() removes all items from the dictionary.

Syntax
dict.clear()

Parameters
NA

Return Value
This method does not return any value.

For Example
>>>dict = {'Name': 'Zara', 'Age': 7}
>>>print ("Start Len : %d" % len(dict))
Start Len : 2
>>>dict.clear()
>>>print ("End Len : %d" % len(dict))
End Len : 0
6. Python dictionary copy() Method :- The method copy() returns a shallow copy of
the dictionary.

Syntax
dict.copy()

Parameters
NA

Return Value
This method returns a shallow copy of the dictionary.

For Example
>>>dict1 = {'Name': 'Zara', 'Age': 7}
>>>dict2 = dict1.copy()
>>>print ("New Dictinary : %s" % str(dict2))
New Dictinary : {'Name': 'Zara', 'Age': 7}
By "shallow copying" it means the content of the dictionary is not copied by value, but just
creating a new reference.
>>> a = {1: [1,2,3]}
>>> b = a.copy()
>>> a, b
({1: [1, 2, 3]}, {1: [1, 2, 3]})
>>> a[1].append(4)
>>> a, b
({1: [1, 2, 3, 4]}, {1: [1, 2, 3, 4]})

In contrast, a deep copy will copy all contents by value.


>>> import copy
>>> c = copy.deepcopy(a)
>>> a, c
({1: [1, 2, 3, 4]}, {1: [1, 2, 3, 4]})
>>> a[1].append(5)
>>> a, c
({1: [1, 2, 3, 4, 5]}, {1: [1, 2, 3, 4]})
7. Python dictionary fromkeys() Method :- The
method fromkeys() creates a new dictionary with keys
from seq and values set to value.

Syntax
dict.fromkeys(seq[, value])

Parameters
seq -- This is the list of values which would be used for dictionary keys
preparation.
value -- This is optional, if provided then value would be set to this value

Return Value
This method returns the list.
Example
>>>seq = ('name', 'age', 'sex')
>>>dict = dict.fromkeys(seq)
>>>print ("New Dictionary : %s" % str(dict))
New Dictionary : {'age': None, 'name': None, 'sex': None}

>>>dict = dict.fromkeys(seq, 10)


print ("New Dictionary : %s" % str(dict))
New Dictionary : {'age': 10, 'name': 10, 'sex': 10}
8. Python dictionary get() Method :- The method get() returns a value for the given key. If key is not available
then returns default value None.

Syntax
dict.get(key, default=None)

Parameters
key -- This is the Key to be searched in the dictionary.
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.

For Example
>>>dict = {'Name': 'Zara', 'Age': 7}
>>>print ("Value : %s" % dict.get('Age'))
Value : 7
>>>print ("Value : %s" % dict.get('Education', "Never"))
Value : Never
9. Python dictionary has_key() Method :- The method has_key() returns true if a given key is available
in the dictionary, otherwise it returns a false.

Syntax
dict.has_key(key)

Parameters
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.

Example
>>>dict = {'Name': 'Zara', 'Age': 7}
>>>print ("Value : %s" % dict.has_key('Age'))
Value : True
>>>print ("Value : %s" % dict.has_key('Sex'))
Value : False
10. Python dictionary items() Method :- The method items() returns a list of dict's
(key, value) tuple pairs

Syntax
dict.items()

Parameters
NA

Return Value
This method returns a list of tuple pairs.

For Example
>>>dict = {'Name': 'Zara', 'Age': 7}
>>>print ("Value : %s" % dict.items())
Value : dict_items([('Name', 'Zara'), ('Age', 7)])
11. Python dictionary keys() Method :- The method keys() returns a list of all the
available keys in the dictionary.

Syntax
dict.keys()

Parameters
NA

Return Value
This method returns a list of all the available keys in the dictionary.

For Example
>>>dict = {'Name': 'Zara', 'Age': 7}
>>>print ("Value : %s" % dict.keys())
Value : dict_keys(['Name', 'Age'])
12. Python dictionary setdefault() Method :- The method setdefault() is similar to

get(), but will set dict[key]=default if key is not already in dict.

Syntax

dict.setdefault(key, default=None)

Parameters

key -- This is the key to be searched.

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.

For Example

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

>>>print ("Value : %s" % dict.setdefault('Age'))

Value : 7

>>>print ("Value : %s" % dict.setdefault('Sex'))

Value : None
13. Python dictionary update() Method :- The method update() adds dictionary dict2's key-values pairs
in to dict. This function does not return anything.

Syntax
dict.update(dict2)

Parameters
dict2 -- This is the dictionary to be added into dict.

Return Value
This method does not return any value.

For Example
>>>dict = {'Name': 'Zara', 'Age': 7}
>>>dict2 = {'Sex': 'female' }
>>>dict.update(dict2)
>>>print ("Value : %s" % dict)
Value : {'Age': 7, 'Name': 'Zara', 'Sex': 'female'}
14. Python dictionary values() Method :- The method values() returns a list of all the
values available in a given dictionary.

Syntax
dict.values()

Parameters
NA

Return Value
This method returns a list of all the values available in a given dictionary.

For Example
>>>dict = {'Name': 'Zara', 'Age': 7}
>>>print ("Value : %s" % dict.values())
Value : [7, 'Zara']

You might also like