SlideShare a Scribd company logo
Dictionaries
Team Emertxe
Dictionaries
Introduction
Group of items arranged in the form of key-value pair
Example
d = {"Name": "Ram", "ID": 102, "Salary": 10000}
Program
#Print the entire dictionary
print(d)
#Print only the keys
print("Keys in dic: ", d.keys())
#Print only values
print("Values: ", d.values())
#Print both keys and value pairs as tuples
print(d.items())
Dictionaries
Operations
d = {"Name": "Ram", "ID": 102, "Salary": 10000}
1. To get the no. of pairs in the Dictionary n = len(d)
2. To modify the existing value d[salary] = 15000
3. To insert new key:value pair d["Dept"] = "Finance"
4. To delete the key:value pair del d["ID"]
5. To check whether the key is present in
dictionary
"Dept" in d
- Returns True, if it is present
6. We can use any datatype fro values, but keys should obey the rules
R1: Keys should be unique
Ex: emp = {10: "Ram", 20: "Ravi", 10: "Rahim"}
- Old value will be overwritten,
emp = {10: "Rahim", 20: "Ravi"}
R2: Keys should be immutable type. Use numbers, strings or tuples
If mutable keys are used, will get 'TypeError'
Dictionaries
Methods
clear() d.clear() Removes all key-value pairs from the d
copy() d1 = d.copy() Copies all items from ‘d’ into a new dictionary ‘d1’
fromkeys() d.fromkeyss(s, [,v])
Create a new dictionary with keys from sequence ‘s’ and
values all set to ‘v’
get() d.get(k, [,v])
Returns the value associated with key ‘k’.
If key is not found, it returns ‘v’
items() d.items()
Returns an object that contains key-value pairs of ‘d’.
The pairs are stored as tuples in the object
keys() d.keys() Returns a sequence of keys from the dictionary ‘d’
values() d.values() Returns a sequence of values from the dictionary ‘d’
update() d.update(x) Adds all elements from dictionary ‘x’ to ‘d’
pop() d.pop(k, [,v]) Removes the key ‘k’ and its value.
Dictionaries
Programs
To create the dictionary with employee details
d = {"Name": "Ram", "ID": 1023, "Salary": 10000}
#Print the entire dictionary
print(d)
#Print only the keys
print("Keys in dic: ", d.keys())
#Print only values
print("Values: ", d.values())
#Print both keys and value pairs as tuples
print(d.items())
Dictionaries
Programs
#To create a dictionary from the keyboard and display the items
x = {}
print("Enter 'n' value: ", end='')
n = int(input())
for i in range(n):
print("Enter the key: ", end='')
k = input()
print("Enter the value: ", end='')
v = int(input())
x.update({k: v})
print(x)
Dictionaries
Using for loop with Dictionaries
Method-1
for k in colors:
print(k)
Method-2
for k in colors:
print(colors[k])
Method-3
for k, v in colors.items():
print("key = {}nValue = {}". format(k, v))
Dictionaries
Sorting Dictionaries: Exercise
To sort the elements of a dictionary based on akey or value
Dictionaries
Converting Lists into Dictionary
Two step procedure
- zip()
- dict()
#To convert list into dictionary
countries = ["India", "USA"]
cities = ["New Delhi", "Washington"]
#Make a dictionary
z = zip(countries, cities)
d = dict(z)
print(d)
Dictionaries
Converting strings into dictionary
str = "Ram=23,Ganesh=20"
#Create the empty list
lst = []
for x in str.split(','):
y = x.split('=')
lst.append(y)
#Convert into dictionary
d = dict(lst)
print(d)
Dictionaries
Passing dictionary to function
By specifying the name of the dictionary as the parameter, we can pass the dictionary to the
function.
Example
d = {10: "Ram"}
display(d)
Dictionaries
Ordered Dictionaries
from collections import OrderedDict
Example
d = {10: "Ram"}
display(d)
Program:
#To create the ordered dictionary
from collections import OrderedDict
#Create empty dictionary
d = OrderedDict()
d[10] = 'A'
d[11] = 'B'
d[12] = 'C'
d[13] = 'D'
print(d)
THANK YOU

More Related Content

What's hot

Python functions
Python functionsPython functions
Python functions
Prof. Dr. K. Adisesha
 
Python Part 1
Python Part 1Python Part 1
Python Part 1
Sunil OS
 
Files and streams
Files and streamsFiles and streams
Files and streams
Pranali Chaudhari
 
Python Pandas
Python PandasPython Pandas
Python Pandas
Sunil OS
 
Numeric Data types in Python
Numeric Data types in PythonNumeric Data types in Python
Numeric Data types in Python
jyostna bodapati
 
Strings in python
Strings in pythonStrings in python
Strings in python
Prabhakaran V M
 
Function in C
Function in CFunction in C
Function in C
Dr. Abhineet Anand
 
Strings in c
Strings in cStrings in c
Strings in c
vampugani
 
Python programming : Files
Python programming : FilesPython programming : Files
Python programming : Files
Emertxe Information Technologies Pvt Ltd
 
C programming - String
C programming - StringC programming - String
C programming - String
Achyut Devkota
 
Python Flow Control
Python Flow ControlPython Flow Control
Python Flow Control
Mohammed Sikander
 
Function in c
Function in cFunction in c
Function in c
savitamhaske
 
Python : Data Types
Python : Data TypesPython : Data Types
Python - Lecture 11
Python - Lecture 11Python - Lecture 11
Python - Lecture 11
Ravi Kiran Khareedi
 
Pointers, virtual function and polymorphism
Pointers, virtual function and polymorphismPointers, virtual function and polymorphism
Pointers, virtual function and polymorphism
lalithambiga kamaraj
 
File handling in C
File handling in CFile handling in C
File handling in C
Kamal Acharya
 
C Basics
C BasicsC Basics
C Basics
Sunil OS
 
Python ppt
Python pptPython ppt
Python ppt
Anush verma
 
Basic Concepts in Python
Basic Concepts in PythonBasic Concepts in Python
Basic Concepts in Python
Sumit Satam
 
List,tuple,dictionary
List,tuple,dictionaryList,tuple,dictionary
List,tuple,dictionary
nitamhaske
 

What's hot (20)

Python functions
Python functionsPython functions
Python functions
 
Python Part 1
Python Part 1Python Part 1
Python Part 1
 
Files and streams
Files and streamsFiles and streams
Files and streams
 
Python Pandas
Python PandasPython Pandas
Python Pandas
 
Numeric Data types in Python
Numeric Data types in PythonNumeric Data types in Python
Numeric Data types in Python
 
Strings in python
Strings in pythonStrings in python
Strings in python
 
Function in C
Function in CFunction in C
Function in C
 
Strings in c
Strings in cStrings in c
Strings in c
 
Python programming : Files
Python programming : FilesPython programming : Files
Python programming : Files
 
C programming - String
C programming - StringC programming - String
C programming - String
 
Python Flow Control
Python Flow ControlPython Flow Control
Python Flow Control
 
Function in c
Function in cFunction in c
Function in c
 
Python : Data Types
Python : Data TypesPython : Data Types
Python : Data Types
 
Python - Lecture 11
Python - Lecture 11Python - Lecture 11
Python - Lecture 11
 
Pointers, virtual function and polymorphism
Pointers, virtual function and polymorphismPointers, virtual function and polymorphism
Pointers, virtual function and polymorphism
 
File handling in C
File handling in CFile handling in C
File handling in C
 
C Basics
C BasicsC Basics
C Basics
 
Python ppt
Python pptPython ppt
Python ppt
 
Basic Concepts in Python
Basic Concepts in PythonBasic Concepts in Python
Basic Concepts in Python
 
List,tuple,dictionary
List,tuple,dictionaryList,tuple,dictionary
List,tuple,dictionary
 

Similar to Python : Dictionaries

2 UNIT CH3 Dictionaries v1.ppt
2 UNIT CH3 Dictionaries v1.ppt2 UNIT CH3 Dictionaries v1.ppt
2 UNIT CH3 Dictionaries v1.ppt
tocidfh
 
COMPUTER SCIENCE CLASS 12 PRACTICAL FILE
COMPUTER SCIENCE CLASS 12 PRACTICAL FILECOMPUTER SCIENCE CLASS 12 PRACTICAL FILE
COMPUTER SCIENCE CLASS 12 PRACTICAL FILE
Anushka Rai
 
Lecture-6.pdf
Lecture-6.pdfLecture-6.pdf
Lecture-6.pdf
Bhavya103897
 
python practicals-solution-2019-20-class-xii.pdf
python practicals-solution-2019-20-class-xii.pdfpython practicals-solution-2019-20-class-xii.pdf
python practicals-solution-2019-20-class-xii.pdf
rajatxyz
 
第二讲 预备-Python基礎
第二讲 预备-Python基礎第二讲 预备-Python基礎
第二讲 预备-Python基礎
anzhong70
 
第二讲 Python基礎
第二讲 Python基礎第二讲 Python基礎
第二讲 Python基礎
juzihua1102
 
Xi CBSE Computer Science lab programs
Xi CBSE Computer Science lab programsXi CBSE Computer Science lab programs
Xi CBSE Computer Science lab programs
Prof. Dr. K. Adisesha
 
Python basic
Python basicPython basic
Python basic
Saifuddin Kaijar
 
Basics of Python programming (part 2)
Basics of Python programming (part 2)Basics of Python programming (part 2)
Basics of Python programming (part 2)
Pedro Rodrigues
 
ECE-PYTHON.docx
ECE-PYTHON.docxECE-PYTHON.docx
ECE-PYTHON.docx
Chaithanya89350
 
Dictionary in python
Dictionary in pythonDictionary in python
Dictionary in python
vikram mahendra
 
Python dictionaries
Python dictionariesPython dictionaries
Python dictionaries
Krishna Nanda
 
PyLecture4 -Python Basics2-
PyLecture4 -Python Basics2-PyLecture4 -Python Basics2-
PyLecture4 -Python Basics2-
Yoshiki Satotani
 
R basic programs
R basic programsR basic programs
R basic programs
Priya Shetty
 
solution-of-practicals-class-xii-comp.-sci.-083-2021-22 (1).pdf
solution-of-practicals-class-xii-comp.-sci.-083-2021-22 (1).pdfsolution-of-practicals-class-xii-comp.-sci.-083-2021-22 (1).pdf
solution-of-practicals-class-xii-comp.-sci.-083-2021-22 (1).pdf
parthp5150s
 
python_lab_manual_final (1).pdf
python_lab_manual_final (1).pdfpython_lab_manual_final (1).pdf
python_lab_manual_final (1).pdf
keerthu0442
 
Poetry with R -- Dissecting the code
Poetry with R -- Dissecting the codePoetry with R -- Dissecting the code
Poetry with R -- Dissecting the code
Peter Solymos
 
STRING LIST TUPLE DICTIONARY FILE.pdf
STRING LIST TUPLE DICTIONARY FILE.pdfSTRING LIST TUPLE DICTIONARY FILE.pdf
STRING LIST TUPLE DICTIONARY FILE.pdf
omprakashmeena48
 
Common problems solving using c
Common problems solving using cCommon problems solving using c
Common problems solving using c
ArghodeepPaul
 
C# Summer course - Lecture 2
C# Summer course - Lecture 2C# Summer course - Lecture 2
C# Summer course - Lecture 2
mohamedsamyali
 

Similar to Python : Dictionaries (20)

2 UNIT CH3 Dictionaries v1.ppt
2 UNIT CH3 Dictionaries v1.ppt2 UNIT CH3 Dictionaries v1.ppt
2 UNIT CH3 Dictionaries v1.ppt
 
COMPUTER SCIENCE CLASS 12 PRACTICAL FILE
COMPUTER SCIENCE CLASS 12 PRACTICAL FILECOMPUTER SCIENCE CLASS 12 PRACTICAL FILE
COMPUTER SCIENCE CLASS 12 PRACTICAL FILE
 
Lecture-6.pdf
Lecture-6.pdfLecture-6.pdf
Lecture-6.pdf
 
python practicals-solution-2019-20-class-xii.pdf
python practicals-solution-2019-20-class-xii.pdfpython practicals-solution-2019-20-class-xii.pdf
python practicals-solution-2019-20-class-xii.pdf
 
第二讲 预备-Python基礎
第二讲 预备-Python基礎第二讲 预备-Python基礎
第二讲 预备-Python基礎
 
第二讲 Python基礎
第二讲 Python基礎第二讲 Python基礎
第二讲 Python基礎
 
Xi CBSE Computer Science lab programs
Xi CBSE Computer Science lab programsXi CBSE Computer Science lab programs
Xi CBSE Computer Science lab programs
 
Python basic
Python basicPython basic
Python basic
 
Basics of Python programming (part 2)
Basics of Python programming (part 2)Basics of Python programming (part 2)
Basics of Python programming (part 2)
 
ECE-PYTHON.docx
ECE-PYTHON.docxECE-PYTHON.docx
ECE-PYTHON.docx
 
Dictionary in python
Dictionary in pythonDictionary in python
Dictionary in python
 
Python dictionaries
Python dictionariesPython dictionaries
Python dictionaries
 
PyLecture4 -Python Basics2-
PyLecture4 -Python Basics2-PyLecture4 -Python Basics2-
PyLecture4 -Python Basics2-
 
R basic programs
R basic programsR basic programs
R basic programs
 
solution-of-practicals-class-xii-comp.-sci.-083-2021-22 (1).pdf
solution-of-practicals-class-xii-comp.-sci.-083-2021-22 (1).pdfsolution-of-practicals-class-xii-comp.-sci.-083-2021-22 (1).pdf
solution-of-practicals-class-xii-comp.-sci.-083-2021-22 (1).pdf
 
python_lab_manual_final (1).pdf
python_lab_manual_final (1).pdfpython_lab_manual_final (1).pdf
python_lab_manual_final (1).pdf
 
Poetry with R -- Dissecting the code
Poetry with R -- Dissecting the codePoetry with R -- Dissecting the code
Poetry with R -- Dissecting the code
 
STRING LIST TUPLE DICTIONARY FILE.pdf
STRING LIST TUPLE DICTIONARY FILE.pdfSTRING LIST TUPLE DICTIONARY FILE.pdf
STRING LIST TUPLE DICTIONARY FILE.pdf
 
Common problems solving using c
Common problems solving using cCommon problems solving using c
Common problems solving using c
 
C# Summer course - Lecture 2
C# Summer course - Lecture 2C# Summer course - Lecture 2
C# Summer course - Lecture 2
 

More from Emertxe Information Technologies Pvt Ltd

Career Transition (1).pdf
Career Transition (1).pdfCareer Transition (1).pdf
Career Transition (1).pdf
Emertxe Information Technologies Pvt Ltd
 
10_isxdigit.pdf
10_isxdigit.pdf10_isxdigit.pdf

More from Emertxe Information Technologies Pvt Ltd (20)

premium post (1).pdf
premium post (1).pdfpremium post (1).pdf
premium post (1).pdf
 
Career Transition (1).pdf
Career Transition (1).pdfCareer Transition (1).pdf
Career Transition (1).pdf
 
10_isxdigit.pdf
10_isxdigit.pdf10_isxdigit.pdf
10_isxdigit.pdf
 
01_student_record.pdf
01_student_record.pdf01_student_record.pdf
01_student_record.pdf
 
02_swap.pdf
02_swap.pdf02_swap.pdf
02_swap.pdf
 
01_sizeof.pdf
01_sizeof.pdf01_sizeof.pdf
01_sizeof.pdf
 
07_product_matrix.pdf
07_product_matrix.pdf07_product_matrix.pdf
07_product_matrix.pdf
 
06_sort_names.pdf
06_sort_names.pdf06_sort_names.pdf
06_sort_names.pdf
 
05_fragments.pdf
05_fragments.pdf05_fragments.pdf
05_fragments.pdf
 
04_magic_square.pdf
04_magic_square.pdf04_magic_square.pdf
04_magic_square.pdf
 
03_endianess.pdf
03_endianess.pdf03_endianess.pdf
03_endianess.pdf
 
02_variance.pdf
02_variance.pdf02_variance.pdf
02_variance.pdf
 
01_memory_manager.pdf
01_memory_manager.pdf01_memory_manager.pdf
01_memory_manager.pdf
 
09_nrps.pdf
09_nrps.pdf09_nrps.pdf
09_nrps.pdf
 
11_pangram.pdf
11_pangram.pdf11_pangram.pdf
11_pangram.pdf
 
10_combinations.pdf
10_combinations.pdf10_combinations.pdf
10_combinations.pdf
 
08_squeeze.pdf
08_squeeze.pdf08_squeeze.pdf
08_squeeze.pdf
 
07_strtok.pdf
07_strtok.pdf07_strtok.pdf
07_strtok.pdf
 
06_reverserec.pdf
06_reverserec.pdf06_reverserec.pdf
06_reverserec.pdf
 
05_reverseiter.pdf
05_reverseiter.pdf05_reverseiter.pdf
05_reverseiter.pdf
 

Recently uploaded

Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 

Recently uploaded (20)

Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 

Python : Dictionaries

  • 2. Dictionaries Introduction Group of items arranged in the form of key-value pair Example d = {"Name": "Ram", "ID": 102, "Salary": 10000} Program #Print the entire dictionary print(d) #Print only the keys print("Keys in dic: ", d.keys()) #Print only values print("Values: ", d.values()) #Print both keys and value pairs as tuples print(d.items())
  • 3. Dictionaries Operations d = {"Name": "Ram", "ID": 102, "Salary": 10000} 1. To get the no. of pairs in the Dictionary n = len(d) 2. To modify the existing value d[salary] = 15000 3. To insert new key:value pair d["Dept"] = "Finance" 4. To delete the key:value pair del d["ID"] 5. To check whether the key is present in dictionary "Dept" in d - Returns True, if it is present 6. We can use any datatype fro values, but keys should obey the rules R1: Keys should be unique Ex: emp = {10: "Ram", 20: "Ravi", 10: "Rahim"} - Old value will be overwritten, emp = {10: "Rahim", 20: "Ravi"} R2: Keys should be immutable type. Use numbers, strings or tuples If mutable keys are used, will get 'TypeError'
  • 4. Dictionaries Methods clear() d.clear() Removes all key-value pairs from the d copy() d1 = d.copy() Copies all items from ‘d’ into a new dictionary ‘d1’ fromkeys() d.fromkeyss(s, [,v]) Create a new dictionary with keys from sequence ‘s’ and values all set to ‘v’ get() d.get(k, [,v]) Returns the value associated with key ‘k’. If key is not found, it returns ‘v’ items() d.items() Returns an object that contains key-value pairs of ‘d’. The pairs are stored as tuples in the object keys() d.keys() Returns a sequence of keys from the dictionary ‘d’ values() d.values() Returns a sequence of values from the dictionary ‘d’ update() d.update(x) Adds all elements from dictionary ‘x’ to ‘d’ pop() d.pop(k, [,v]) Removes the key ‘k’ and its value.
  • 5. Dictionaries Programs To create the dictionary with employee details d = {"Name": "Ram", "ID": 1023, "Salary": 10000} #Print the entire dictionary print(d) #Print only the keys print("Keys in dic: ", d.keys()) #Print only values print("Values: ", d.values()) #Print both keys and value pairs as tuples print(d.items())
  • 6. Dictionaries Programs #To create a dictionary from the keyboard and display the items x = {} print("Enter 'n' value: ", end='') n = int(input()) for i in range(n): print("Enter the key: ", end='') k = input() print("Enter the value: ", end='') v = int(input()) x.update({k: v}) print(x)
  • 7. Dictionaries Using for loop with Dictionaries Method-1 for k in colors: print(k) Method-2 for k in colors: print(colors[k]) Method-3 for k, v in colors.items(): print("key = {}nValue = {}". format(k, v))
  • 8. Dictionaries Sorting Dictionaries: Exercise To sort the elements of a dictionary based on akey or value
  • 9. Dictionaries Converting Lists into Dictionary Two step procedure - zip() - dict() #To convert list into dictionary countries = ["India", "USA"] cities = ["New Delhi", "Washington"] #Make a dictionary z = zip(countries, cities) d = dict(z) print(d)
  • 10. Dictionaries Converting strings into dictionary str = "Ram=23,Ganesh=20" #Create the empty list lst = [] for x in str.split(','): y = x.split('=') lst.append(y) #Convert into dictionary d = dict(lst) print(d)
  • 11. Dictionaries Passing dictionary to function By specifying the name of the dictionary as the parameter, we can pass the dictionary to the function. Example d = {10: "Ram"} display(d)
  • 12. Dictionaries Ordered Dictionaries from collections import OrderedDict Example d = {10: "Ram"} display(d) Program: #To create the ordered dictionary from collections import OrderedDict #Create empty dictionary d = OrderedDict() d[10] = 'A' d[11] = 'B' d[12] = 'C' d[13] = 'D' print(d)