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

Review of Python-Dictionary (1)

The document provides an overview of dictionaries in Python, describing them as unordered collections of key-value pairs that are mutable and require unique keys. It covers how to create, access, update, and remove items from dictionaries, along with various built-in functions and methods for manipulating them. Examples are provided to illustrate the syntax and functionality of dictionaries.

Uploaded by

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

Review of Python-Dictionary (1)

The document provides an overview of dictionaries in Python, describing them as unordered collections of key-value pairs that are mutable and require unique keys. It covers how to create, access, update, and remove items from dictionaries, along with various built-in functions and methods for manipulating them. Examples are provided to illustrate the syntax and functionality of dictionaries.

Uploaded by

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

Dictionaries in Python

Introduction
 Dictionary is an unordered collection (no indexing) of items where each item consist of a
key and a value, ie.,key-value pair.
 If we want to group multiple elements under a single variable, these datatypes or
collections are used in Python.
 Each element in a dictionary can be accessed by a unique key.
 It is mutable(can modify its values), but key must be unique and immutable.

{Key:Value} Keys strings,numbers or tuples.


Values can be of any python datatypes
 Each key is separated from its value by a colon( : ),items are separated by commas, and
entire dictionary is enclosed in curly braces.
Creating a Dictionary
 Syntax:
<dictionary_name={‘key1’:’Value1’,’key2’:’value2’,………’keyn’:’valuen’}
 Example: d={} Empty dictionary
Values

dict={‘R’:’Rainy’,’S’:’Summer’,’W’:’Winter’,’A’:’Autumn’}

Keys
print(dict)
Output is {'R': 'Rainy', 'S': 'Summer', 'W': 'Winter', 'A': 'Autumn’}
dict={‘R’:’Rainy’,’S’:’Summer’,’W’:’Winter’,’A’:’Autumn’,’W’:’Winter Season’}
print(dict)
Output is {'R': 'Rainy', 'S': 'Summer', 'W': 'Winter Season', 'A': 'Autumn'}
Methods to create a Dictionary
1.To create an empty dictionary, put two curly braces:
Example: >>>d={}
>>>type(d)
<class ‘dict’>
2.Enclose key-value pair in curly braces:
Example: >>>d={‘Name’:’Amy’,’Age’:16,’Class’:11}
>>>print(d)
{‘Name’:’Amy’,’Age’:16,’Class’:12}
3.Using dict():
Add an item to a dictionary
 To add an item to a dictionary, we can use square bracket([])
for accessing and initializing dictionary values.
 Example: >>>d={}
>>>d[1]=“One”
>>>d[2]=“Two”
>>>d[3]=“Three”
>>>print(d)
{1:”One”,2:”Two”,3:”Three”}
Accessing Elements in Dictionary
 To access dictionary elements, we can use square brackets along with the key to obtain its
value.
 Example:
>>>d={‘Name’:’Riya’,’Age’:7,’Class’:’Second’}
>>>print(d[‘Name’] or print(“d[‘Name’]:“,d[‘Name’]) or print(d.get(‘Name’))
Riya
>>>print(d[‘Age’] or print(“d[‘Age’]:”,d[‘Age’]) or print(d.get(‘Age’))
7
 If we try to access element with a key which is not a part of dictionary, we get an error as
follows:
>>>d={‘Name’:’Riya’,’Age’:7,’Class’:’Second’}
>>>print(d[‘Aman’]
Traceback (most recent call last)
File”<pyshell#16>”,line 1,in <module>
print(d[‘Aman’]
Key error:’Aman’
Traversing a Dictionary
 Traversing a dictionary means accessing each element in a dictionary.
 This can be done through for loops.
 Example 1:
d={1:’One’,2:’Two’,3:’Three’} Output 1 One
for i in d: # i takes the key not values. 2 Two
print(i,d[i]) 3 Three
 Example 2:
d={1:’One’,2:’Two’,3:’Three’} Output 1:One
for i in d: # i takes the key not values. 2:Two
print(i,”:”,d[i]) 3:Three
Appending Values in a dictionary
 We can add elements to an existing dictionary.
 Example:
D={‘Sun’:’Sunday’,’Mon’:’Monday’}
D[‘Tue’]=‘Tuesday’
print(D)

Output
{‘Sun’:’Sunday’,’Mon’:’Monday’,’Tue’:’Tuesday’}
Updating Dictionary Elements
 We can modify the individual elements of a dictionary.
 Example:
d={‘Teena’:18,’Riya’:12,’Ameya’:22,’Ram’:25}
d[‘Riya’]=28
print(d) Output {‘Teena’:18,’Riya’:28,’Ameya’:22,’Ram’:25}
 Two dictionaries can be merged into one by using update() method.
 Example:
d1={1:10,2:20,3:30}
d2={4:40,5:50}
print(d1.update(d2)) Output {1:10,2:20,3:30,4:40,5:50}
 Example:
d1=={1:10,2:30,3:30,5:40,6:60}
d2={1:10,2:20,3:30}
print(d1.update(d2)) Output {1:10,2:203:30,5:40,6:60}
Removing an item from Dictionary
Using del command:
 Example:
A={‘Mon’:’Monday’,’Tue’:’Tuesday’,’Wed’:’Wednesday’,’Thur’:’Thursday’}
print(del A[‘Wed’]) Output {‘Mon’:’Monday’,’Tue’:’Tuesday’,’Thur’:’Thursday’}
print(del A[‘Fri’]) KeyError:’Fri’

Using pop() method:


 pop() method not only delete the item from the dictionary, but also return the deleted
value.
 Example:
A={‘Mon’:’Monday’,’Tue’:’Tuesday’,’Wed’:’Wednesday’,’Thur’:’Thursday’}
d=A.pop(‘Tue’)
print (d) Output Tuesday
print(A) Output {‘Mon’:’Monday’,’Wed’:’Wednesday’,’Thur’:’Thursday’}
Using popitem() method:
 Python dictionary popitem() method removes the last inserted key-
value pair from the dictionary and returns it as a tuple.
 popitem() method return keyError if dictionary is empty.
 Example:
d = {1: '001', 2: '010', 3: '011’}
print(d.popitem()) Output is (3, ’011’)
‘in’ & ‘not in’ Membership Operator
 It checks whether a particular key is present in the dictionary or not.
 It returns True if element appears in the dictionary, otherwise returns False.
 Example:
>>>d={‘mon’:’Monday’,’tue’:’tuesday’,’wed’:’Wednesday’}
>>>‘thur’ in d
False
>>>’mon’ in d
True
Dictionary Built-in Functions
len():
 It returns the number of key-value pairs in the given dictionary.
 Example:
>>>d1={1:10,2:30,3:30,5:40,6:60}
>>>len(d1)
5
clear():
 It removes all items from a particular dictionary.
 Example:
>>>d1={1:10,2:30,3:30,5:40,6:60}
>>>d1.clear()
>>>print(d1)
{}
get():
 It returns a value for the given key.
 Syntax:
dict.get(key,default=None)
key- This is the key to be searched in the dictionary.
default-This is the value to be returned if the key does not exists.
 Example:
>>>d={‘Sun’:’Sunday’,’Mon’:’Monday’,’Tue’:’Tuesday’,’Wed’:’Wednesday’}
>>>d.get(‘Tue’)
Tuesday
>>>d.get(‘Fri’)
None
 We can specify our own message for default value.
>>>d.get(‘Fri’,’Never’)
Never
items():
 It returns the content of dictionary as a list of tuples having key-value pairs.
 Example:
>>>d={‘Sun’:’Sunday’,’Mon’:’Monday’,’Tue’:’Tuesday’,’Wed’:’Wednesday’}
>>>d.items()
dict_items([(‘Sun’,’Sunday’),(‘Mon’,’Monday’),(‘Tue’,’Tuesday’),(‘Wed’,’Wednesday’)])

keys():
 It returns a list of key values in the dictionary.
 Example:
>>>d={‘Sun’:’Sunday’,’Mon’:’Monday’,’Tue’:’Tuesday’,’Wed’:’Wednesday’}
>>>d.keys()
dict_items([‘Sun’,’Mon’,’Tue’,’Wed’])
values():
 It returns a list of values from key-value pairs in a dictionary.
 Example:
>>>d={‘Sun’:’Sunday’,’Mon’:’Monday’,’Tue’:’Tuesday’,’Wed’:’Wednesday’}
>>>d.values()
dict_items([‘Sunday’,’Monday’,’Tuesday’,’Wednesday’])

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy