0% found this document useful (0 votes)
12 views48 pages

Python (Dictionary)

The document provides a comprehensive overview of Python dictionaries, detailing their structure as unordered collections of key-value pairs, where keys must be unique and immutable. It covers how to create, access, update, and delete dictionary elements, along with various methods for manipulating dictionaries, such as using the 'get()', 'pop()', and 'clear()' functions. Additionally, it explains the use of membership operators to check for key existence and describes several dictionary functions and methods.

Uploaded by

Khushi Sharma
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)
12 views48 pages

Python (Dictionary)

The document provides a comprehensive overview of Python dictionaries, detailing their structure as unordered collections of key-value pairs, where keys must be unique and immutable. It covers how to create, access, update, and delete dictionary elements, along with various methods for manipulating dictionaries, such as using the 'get()', 'pop()', and 'clear()' functions. Additionally, it explains the use of membership operators to check for key existence and describes several dictionary functions and methods.

Uploaded by

Khushi Sharma
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/ 48

 It is an unordered collection of items where each item consist of

a key and a value.(it is collection of some key-value pairs)


 It is mutable (can modify its contents ) but Key must be unique
and immutable.

 Creating A Dictionary :
 It is enclosed in curly braces {} and each item is separated from
other item by a comma(,). Within each item, key and value are
separated by a colon (:).
 Passing value in dictionary at declaration is dictionary
initialization. get() method is used to access value of a key
Syntax:

<dictionary name>={<key1>:<value1>, <key2>:<value12>,…..}

e.g.
Report={‘Rno’:1,’Name’:’Khusbu’,’Marks’:99}
Note:
 The curly brackets mark the beginning and end of the dictionary.
 Each entry (Key :Value) consists of a pair separated by a colon-the
key and corresponding value is given by writing colon(:) between
them.
 The key-value pairs are separated by commas(,).
Note: Dictionaries are indexed (i.e. arranged) on the basis of keys
Features of Dictionary:
1.Unordered set: dictionary is a unordered collection of key : value
pairs.
2. Not a sequence: like list, string and tuple , it is not a sequence
because it is a collection of unordered elements whereas a sequence is
a collection of indexed numbers to keep them in order.

3. Keys are used for its indexing because according to Python key can
be of immutable type. String and numbers are of immutable type and
therefore can be used as a key.
Note: Key of a Dictionary should always be of immutable type like
number, string or tuple whereas value of a dictionary can be of any
type.
Features of Dictionary:
4.Keys should be unique : Because keys are used to identify values so
they should be unique.
5. Values of two unique keys can be same.
6. Dictionary is mutable hence we can change value of a certain key.
Syntax is-
dict={"k1":"AAA","k2":"BBB","k3":"CCC"}
print(dict)
dict["k1"]="KKK" {'k1': 'AAA', 'k2': 'BBB', 'k3': 'CCC'}
print(dict) {'k1': 'KKK', 'k2': 'BBB', 'k3': 'CCC'}

Note: Internally it is stored as a mapping. Its key:value are connected to each other via an
internal function called hash function(Hash-function is an internal algorithm to link a key and its
value).
Such process of linking is knows as mapping.
Notes:
 One thing to be taken care of is that keys should always be of
immutable type.
 Dictionary is also known as associative array or mapping or hashes.
 If you try to make keys as mutable, python shown error in it.
e.g., dict={(3,4):"AAA",3:345,"sub":"comp"}
Print(dict)
Output:
{(3, 4): 'AAA', 3: 345, 'sub': 'comp'} Here error shows
that you are
trying to create a
dict5={[3,4]:"AAA"} key of mutable
type which is not
TypeError: unhashable type: 'list' permitted.
There are two ways to create an empty dictionary
1. <name of dictionary> = { }
2. <name of dictionary> = dict( ) dict( ) constructor is used
to create dictionary with
e.g. the pairs of key and value.

s1={}
s1['R1']="kiran"
s1['R2']="khusbu“
s1[2]="Deepa" Output:
print(s1) {'R1': 'kiran', 'R2': 'khusbu', 2: 'Deepa'}
continue....
More methods to create dictionary by using dict( )
1) By passing Key:value pair as an argument:
s=dict(Name="Viki",Sal=50000,Age=26)
print(s)
2) By specifying Comma-separated key:value pair
s2=dict({1:"Reema",2:"Reena"})
print(s2)

Output:
{'Name': 'Viki', 'Sal': 50000, 'Age': 26}
{1: 'Reema', 2: 'Reena'}
More methods to create dictionary by using dict( )
3) By specifying Keys and values separately: For this, we
use zip() function in dict ( ) constructor.

s=dict(zip(("Name","Sal","Age"),("Viki",50000,26)))
print(s)

Output:
{'Name': 'Viki', 'Sal': 50000, 'Age': 26}
More methods to create dictionary by using dict( )
4) By giving Key:value pair in the form of separate sequence:
s1=dict([["Name","Viki"],["Sal",50000],["Age",26]])
s2=dict((["Add","Jsg"],["State","Odisha"],["Pin",768201]))
s3=dict(((1,"Hello"),(2,"Bye"),(3,"Thank U")))
print(s1) By passing List

print(s2) By passing tuple of tuple By passing tuple of a list


print(s3)
Output:
{'Name': 'Viki', 'Sal': 50000, 'Age': 26}
{'Add': 'Jsg', 'State': 'Odisha', 'Pin': 768201}
{1: 'Hello', 2: 'Bye', 3: 'Thank U'}
Adding an element in Dictionary:
s3=dict(((1,"Hello"),(2,"Bye"),(3,"Thank U")))
print(s3)
s3[4]="welcome"
print(s3)

Output:
{1: 'Hello', 2: 'Bye', 3: 'Thank U'}
{1: 'Hello', 2: 'Bye', 3: 'Thank U', 4: 'welcome'}
Nested Dictionary:
Res={"Reena":{"Mk":95,"Gr":"A"},"Lalit":{"Mk":85,"Gr":"B"}}
for key in Res:
print("Name-",key);
print("Marks-",Res[key]['Mk'])
print("Grade-",Res[key]['Gr'])
Output:
Name- Reena
Marks- 95
Grade- A
Name- Lalit dic2021
Marks- 85
Grade- B
# Creating an empty Dictionary :
Dict = {} Empty Dictionary:
print("Empty Dictionary: ") {}
print(Dict)
# Creating a Dictionary with Integer Keys Dictionary with the use of Integer Keys:
Dict = {1: 'AAA', 2: 'BBB', 3: 'CCC'} {1: 'AAA', 2: 'BBB', 3: 'CCC'}
print("\nDictionary with the use of Integer Keys: ")
print(Dict) Dictionary with the use of Mixed Keys:
{'Name': 'Govind', 1: [10, 11, 12, 13]}
# Creating a Dictionary with Mixed keys
Dict = {'Name': 'Govind', 1: [10, 11, 12, 13]}
Dictionary with the use of dict():
print("\nDictionary with the use of Mixed Keys: ") {1: 'AAA', 2: 'BBB', 3: 'CCC'}
print(Dict)
# Creating a Dictionary with dict() method Dictionary with each item as a pair:
D=dict({1: 'AAA', 2: 'BBB', 3:'CCC'}) {1: 'AAA', 2: 'BBB'}
print("\nDictionary with the use of dict(): ")
print(D)
dict,EXAMPLE2021.py
# Creating a Dictionary with each item as a Pair
D=dict([(1, 'AAA'), (2, 'BBB')])
print("\nDictionary with each item as a pair: ")
print(D)
Dict = {}
print(Dict)
# Adding elements one at a time
Dict[1] = 'Govind'
Dict[2] = 'Prasad' {}
Dict[3] = 'Arya'
print("\nDictionary after adding 3 elements: ") Dictionary after adding 3 elements:
print(Dict) {1: 'Govind', 2: 'Prasad', 3: 'Arya'}
# Adding set of values
# to a single Key Dictionary after adding 3 elements:
Dict['V'] = 1, 2 {1: 'Govind', 2: 'Prasad', 3: 'Arya', 'V': (1, 2)}
print("\nDictionary after adding2 elements: ")
Updated dictionary:
print(Dict) {1: 'Govind', 2: 'Prasad', 3: 'Arya', 'V': (3, 4)}
# Updating existing Key's Value
Dict['V'] = 3,4 dict,EXAMPLE(1)2021.py
print("\nUpdated dictionary: ")
print(Dict)
# Creating a Dictionary
D = {1: 'Prasad', 'name': 'Govind', 3: 'Arya'}

# accessing a element using key Accessing a element using key:


print("Accessing a element using key:") Govind
print(D['name']) Accessing a element using key:
Prasad
Accessing a element using get( ):
# accessing a element using key Arya
print("Accessing a element using key:")
print(D[1])

# accessing a element using get() method


print("Accessing a element using get( ):") dict,EXAMPLE(2)2021.py

print(D.get(3))
D={1:'AAA', 2:'BBB', 3:'CCC'}
print("\n All key names in the dictionary, one by one:") dict,EXAMPLE(3)2021.py
for i in D: All key names in the dictionary, one by one:
print(i, end=' ') 123
print("\n All values in the dictionary, one by one:")
for i in D: All values in the dictionary, one by one:
print(D[i], end=' ') AAA BBB CCC
print("\n All keys in the dictionary using keys() method:")
for i in D.keys(): All keys in the dictionary using keys() method:
print(i, end=' ') 123
print("\n All values in the dictionary using values() method:")
for i in D.values(): All values in the dictionary using values() method:
print(i, end=' ') AAA BBB CCC
print("\n All keys and values in the dictionary using items()method:")
for k,v in D.items(): All keys and values in the dictionary usingitems()method:
print(k,v, end=' ') 1 AAA 2 BBB 3 CCC
Accessing a Dictionary
• To access a value from dictionary, we need to use key similarly as we
use an index to access a value from a list.
• We get the key from the pair of Key: value.
subject={"sub1":"ENG", "sub2":"COMP","sub3":"MATHS"}
print(subject)
print(subject["sub1"])
print(subject["sub4"])

Output
{'sub1': 'ENG', 'sub2': 'COMP', 'sub3': 'MATHS'}
ENG
print(subject["sub4"])
KeyError: 'sub4'
Iterating / Traversing through A Dictionary
Following example will show how dictionary items can be accessed through loop.
e.g.
dict = {'Class': 12,'Rno':25,'Subject': 'Computer', 'Mark':99}
for i in dict:
print(dict[i])

OUTPUT :
12
25
Computer
99
Updating/Manipulating Dictionary
Elements We can change the individual element of dictionary.
e.g.
dict = {'Subject':'C++','Class':11}
print(dict)
dict['Subject'],dict['Class']='Python',12
print(dict)

OUTPUT
{'Subject': 'C++', 'Class': 11}
{'Subject': 'Python', 'Class': 12}
Deleting Dictionary Elements
del, pop() and clear() statement are used to remove element(s) from
the dictionary.
1) Use of del : To delete a dictionary element or a dictionary
entry(i.e., a Key:Value pair, we can use del command.

Syntax: del <dictionary> [<key>]


e.g.:
D = {'Rno':1,'Name':'Seema','Marks':95}
print(D) {'Rno': 1, 'Name': 'Seema', 'Marks': 95}
del D['Name'] {'Rno': 1, 'Marks': 95}
print(D) del D[‘Name']
del D[‘Name'] KeyError: ‘Name‘
print(D) *Because the key which is given to delete is not
exist in the dictionary
Use of del : We can also use del to delete whole dictionary:

Syntax: del <dictionary>


e.g.:
D = {'Rno':1,'Name':'Seema','Marks':95}
print(D) {'Rno': 1, 'Name': 'Seema', 'Marks': 95}
del D
print(D)
print(D)
NameError: name 'D' is not defined
*Because dictionary is not available
Method-2 : To delete elements from a dictionary we can also use
pop() method.
Syntax: <dictionary>.pop(<key>)

Note : The pop( ) method will not only delete the Key:value pair for
mentioned key but also return the corresponding value.
e.g.
D = {'Rno':1,'Name':'Seema','Marks':95}
print(D) {'Rno': 1, 'Name': 'Seema', 'Marks': 95}
print(D.pop('Marks')) 95
print(D) {'Rno': 1, 'Name': 'Seema'}
print(D.pop('Marks')) print(D.pop('Marks'))
KeyError: 'Marks'
*Because key 'Marks' does not exist
Note : pop() method allows us to specify what to display when
the given key does not exist.

Syntax: <dictionary>.pop(<key>,<error message>)

e.g.:
D = {'Rno':1,'Name':'Seema','Marks':95}
print(D)
print(D.pop('Addr','Not found'))

Output:
{'Rno': 1, 'Name': 'Seema', 'Marks': 95}
Not found
 clear() method is used to remove all elements from the dictionary
The clear() method
Syntax: <dictionary>.clear() removes all the elements of
a dictionary and makes it
e.g.: empty dictionary while del
D = {'Rno':1,'Name':'Seema','Marks':95} statement removes the
print(D) complete dictionary as an
D.clear() # dictionary becomes empty dictionary object.
print(D) After del statement with
dictionary name, that dictionary
Output: object no more exists, not even
empty dictionary.
{'Rno': 1, 'Name': 'Seema', 'Marks': 95}
{}
Checking for existence of a Key:
Basically membership operators in and not in are used with dictionaries to
check the existence of keys.

Syntax: <Key> in <dictionary> # returns True if the given key is present.


<Key> not in <dictionary> # returns True if the given is not present.

e.g.
D = {'S1':'Comp','S2':'Maths','S3':'Eng'}
print(D)
True
print('S2' in D)
print('S5' in D) False
print('S2' not in D) False
print('S5' not in D) True
Dictionary Functions and Methods:

1) len( ) method: This method returns length of the dictionary,


(i.e., the count of elements (key:value pairs) in the dictionary.

Syntax: len(<dictionary>)

e.g.
D = {'S1':'Comp','S2':'Maths','S3':'Eng'}
print(len(D))

OUTPUT:
3
Dictionary Functions and Methods:
2) get( ) method: With this method, we can get the item with the
given key, similar to dictionary[key].(If the key is not present, Python
will give error.

Syntax: <dictionary>.get(key,[default])

e.g.
D = {'S1':'Comp','S2':'Maths','S3':'Eng'}
print(D.get('S2'))

OUTPUT:
Maths
Dictionary Functions and Methods:
3) Items( ) method: This method returns all of the items in the
dictionary as a sequence of (key, value) tuples.
Note: These are returned in no particular order.

Syntax: <dictionary>.items()
OUTPUT
e.g.
D = {'S1':'Comp','S2':'Maths','S3':'Eng'} ('S1', 'Comp')
Li=D.items() ('S2', 'Maths')
for n in Li: ('S3', 'Eng')
print(n)
Dictionary Functions and Methods:
4) keys( ) method: This method returns all of the keys in the
dictionary as a sequence of keys(in form of a list)
Note: These are returned in no particular order.

Syntax: <dictionary>.keys()

e.g.
D = {'S1':'Comp','S2':'Maths','S3':'Eng'}
print(D.keys())
OUTPUT
dict_keys(['S1', 'S2', 'S3'])
Dictionary Functions and Methods:
5) values( ) method: This method returns all of the values in the
dictionary as a sequence.(in form of a list)
Note: These are returned in no particular order.

Syntax: <dictionary>.values()

e.g.
D = {'S1':'Comp','S2':'Maths','S3':'Eng'}
print(D.values())
OUTPUT
dict_values(['Comp', 'Maths', 'Eng'])
Dictionary Functions and Methods:
6) update( ) method: This method merges key:value pairs from the
new dictionary into the original dictionary, adding or replacing as
needed. The items in the new dictionary are added to the old one
and override any items already there with the same keys.

Syntax: <dictionary>.update(<other-dictionary>)
e.g.
D1 ={'M1':90,'M2':69,'M3':92} OUTPUT
D2={'M4':93,'M2':100,'M5':96} {'M1': 90, 'M2': 69, 'M3': 92}
print(D1) {'M4': 93, 'M2': 100, 'M5': 96}
print(D2)
{'M1': 90, 'M2': 100, 'M3': 92, 'M4': 93, 'M5': 96}
D1.update(D2)
print(D1) {'M4': 93, 'M2': 100, 'M5': 96}
print(D2)
Dictionary Functions and Methods:

7) fromkeys() –It is used to create dictionary from keys


keys={'a', 'e', 'i', 'o', 'u' }
value ="Vowel"
vowels=dict.fromkeys(keys,value)
print(vowels)

OUTPUT:
{'i': 'Vowel', 'u': 'Vowel', 'e': 'Vowel', 'a': 'Vowel', 'o': 'Vowel'}
Dictionary Functions and Methods:
8) copy() - returns a copy of the dictionary.
x = dict(name="Kapil",age=25,state="Odisha")
y=x.copy() # deep copy
x['age']=35
print(x)
print(y)
print(id(x)) {'name': 'Kapil', 'age': 35, 'state': 'Odisha'}
print(id(y)) {'name': 'Kapil', 'age': 25, 'state': 'Odisha'}
68423616
68423424
Dictionary Functions and Methods:
8) copy() - returns a copy of the dictionary.
x = dict(name="Kapil",age=25,state="Odisha")
y=x # shallow copy
x['age']=35
print(x)
print(y)
print(id(x)) {'name': 'Kapil', 'age': 35, 'state': 'Odisha'}
print(id(y)) {'name': 'Kapil', 'age': 35, 'state': 'Odisha'}
68423616
68423616
Dictionary Functions and Methods:
9) popitem() – removes last item from dictionary
D ={"Name":"Kapil","Age":25,"State":"Odisha"}
print(D)
m=D.popitem()
print(m)
print(D)

{'Name': 'Kapil', 'Age': 25, 'State': 'Odisha'}


('State', 'Odisha')
{'Name': 'Kapil', 'Age': 25}
Dictionary Functions and Methods:
10)setdefault() method returns the value of the item with the
specified key.
If the key does not exist, insert the key, with the specified value.

D = dict(Sub="Comp",Class=12)
print(D)
n=D.setdefault('age',39) {'Sub': 'Comp', 'Class': 12}
print(D) {'Sub': 'Comp', 'Class': 12, 'age': 39}
n1=D.setdefault('Class',39) 39
print(n) 12
print(n1) {'Sub': 'Comp', 'Class': 12, 'age': 39}
print(D)
Dictionary Functions and Methods:
11) max() – returns key having maximum value.
min()- returns key having minimum value.
D=dict(M1=80,M2=95,M3=99,M4=85)
print(D)
mx=max(D,key=D.get)
mi=min(D,key=D.get)
print(mx)
print(mi)
{{'M1': 80, 'M2': 95, 'M3': 99, 'M4': 85}
M3
M1
Dictionary Functions and Methods:
12) To sort a dictionary by value in Python you can use the sorted()
function. Python's sorted() function can be used to sort dictionaries by key,
which allows for a custom sorting method.
sorted() takes three arguments: object, key, and reverse.
Dictionaries are unordered data structures.

sorted- sort by key or value


dict1 = {'b':100, 'a':12, 'c' : 88}
y = sorted(dict1.items(),key=lambda x: x[1],reverse=True)
print(y)

OUTPUT-> [('b', 100), ('c', 88), ('a', 12)]


Dictionary Functions and Methods:
#sorted- sort by key or value or items
dict1 = {'b':100, 'a':12, 'c' : 88}
y=sorted(dict1.values())
print(y) [12, 88, 100]
y=sorted(dict1.values(),reverse=True)
print(y) [100, 88, 12]
x=sorted(dict1.keys()) ['a', 'b', 'c']
print(x) ['c', 'b', 'a']
x=sorted(dict1.keys(),reverse=True)
print(x)
[('a', 12), ('b', 100), ('c', 88)]
z = sorted(dict1.items()) [('c', 88), ('b', 100), ('a', 12)]
print(z)
z = sorted(dict1.items(),reverse=True)
print(z)
Dictionary Functions and Methods:
13) The method str() produces a printable string representation of a
dictionary.

Syntax: str<Dictionary>
e.g.:
D=dict(M1=80,M2=95,M3=99)
print("Equivalent string-%s"%str(D)) # to get dictionary in printable format

Equivalent string-{'M1': 80, 'M2': 95, 'M3': 99}


Dictionary Functions and Methods:
14) type()-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)
e.g.:
D=dict(M1=80,M2=95,M3=99)
print("Type-%s"%type(D)) Type-<class 'dict'>
D=23 Type-<class 'int'>
print("Type-%s"%type(D))
Dictionary(example-1)
#concatenate dictionaries to create a new one
dic1={1:'AMIT', 2:'VISHAL'}
dic2={3:'MOHAK'}
dic3 = {}
for d in (dic1, dic2):
dic3.update(d)
print(dic3)

OUTPUT:
{1: 'AMIT', 2: 'VISHAL', 3: 'MOHAK'}
Dictionary(example-2)
#to iterate over dictionary
dict ={ "MANGO": "YELLOW", "APPLE": "RED", "GUAVAVA": "GREEN"}
for dkay, dval in dict.items():
print(dkay,'=',dval)

OUTPUT:
MANGO = YELLOW
APPLE = RED
GUAVAVA = GREEN
Dictionary(example-3)

#to sum all the items in a dictionary


dict = {'data1':1,'data2':2,'data3':3}
r=sum(dict.values())
print(r)

OUTPUT:
6
Dictionary(example-3)

#to sort a dictionary by key


dict ={ "MANGO": "YELLOW", "APPLE": "RED", "GUAVAVA":"GREEN"}
for k in sorted(dict):
print("%s: %s" % (k, dict[k]))

OUTPUT:
APPLE: RED
GUAVAVA: GREEN
MANGO: YELLOW
Dictionary(example-4)
#to create a dictionary from a string with frequency of letters
str1 = 'AABBAABSDA'
dict = {}
for lt in str1:
dict[lt] = dict.get(lt, 0) + 1
print(dict)

OUTPUT:
{'A': 5, 'B': 3, 'S': 1, 'D': 1}
Dictionary(example-5)
#to create a dictionary to display marks above 95 also calculate how
have scored.
M={'R1':92,'R2':94,'R3':86,'R4':80,'R5':90,'R6':99,'R7':100,'R8':98}
c=0
for r,m in M.items():
if m>=95:
print(r,m)
c=c+1
print("no of students=",c)
marks,dict.py

You might also like