SlideShare a Scribd company logo
Dictionary in Python
What is a Dictionary in Python?
• A Dictionary in Python is the unordered, and changeable collection of data values that holds
key-value pairs.
• Each key-value pair in the dictionary maps the key to its associated value.
• Python Dictionary is classified into two elements: Keys and Values.
• Keys will be a single element.
• Values can be a list or list within a list, numbers, etc.
Cont..
• Dictionary is ordered or unordered?
• As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries
are unordered.
• When we say that dictionaries are ordered, it means that the items have a defined order,
and that order will not change.
• Unordered means that the items does not have a defined order, you cannot refer to
an item by using an index.
• Dictionary is Changeable:
• Dictionaries are changeable, meaning that we can change, add or remove items
after the dictionary has been created.
• Duplicates Not Allowed in dictionary:
• Dictionaries cannot have two items with the same key
How to Create a Dictionary in Python?
• Dictionary is created with curly brackets, inside these curly brackets, keys and values are declared. Each key is
separated from its value by a colon (:), while commas separate each element.
• A Dictionary in python is declared by enclosing a comma-separated list of key-value pairs using curly braces({}).
• Dictionaries are used to store data values in key:value pairs.
#Creating an empty dictionary
d = {}
#Creating an empty dictionary with the dict function
d = dict()
Cont…
# Initializing a dictionary with values
a = {"a":1 ,"b":2}
b = {'fruit': 'apple', ‘color': ‘red’}
c = {'name': ‘Suchith', 'age’: 20}
d = {'name': ‘Ishanth’, ‘sem’: [1,2,3,7]}
e = {‘branch’:‘CSE’, ‘course’:[‘c’,’java’,’python’]}
f = {'a':1, 'b':2, 'c':3, 'd’:2}
# For Sequence of Key-Value Pairs
g = dict([(1, ‘Apple'), (2, 'Orange'), (3, 'Kiwi')])
Properties of Dictionary Keys
• Keys must be unique: More than one entry per key is not allowed ( no
duplicate key is allowed)
• The values in the dictionary can be of any type, while the keys must be
immutable like numbers, tuples, or strings.
• Dictionary keys are case sensitive- Same key name but with the different
cases are treated as different keys in Python dictionaries.
How to Access Python Dictionary items?
• Since the dictionary is an unordered collection, we can access the values using their
keys.
• It can be done by placing the key in the square brackets or using the get function.
• Ex: Dname[key] or Dname.get(key)
• If we access a non-existing one,
• The get function returns none.
• The key inside a square brackets method throw an error.
Cont..
# Accessing dictionary items
>>> a = {'name': 'Kevin', 'age': 25, 'job': 'Developer’}
# Print
>>> print(a)
{'name': 'Kevin', 'age': 25, 'job': 'Developer’}
>>> print("nName :",a['name’])
Name : Kevin
>>> print("Age : ", a['age’])
Age : 25
>>> print("Job : ", a['job’])
Job : Developer
Cont..
# Accessing dictionary items
>>> a = {'name': 'Kevin', 'age': 25, 'job': 'Developer’}
>>> len(a) #length of dictionary
3
# using get()
>>> print("Name : ", a.get('name’))
Name : Kevin
>>> print("Age : ", a.get('age’))
Age : 25
>>> print("Job : ", a.get('job’))
Job : Developer
Insert and Update Dictionary items
• Remember, dicts are mutable, so you can insert or update any element at any point in time. Use the below
syntax to insert or update values.
DName[key] = value
• If a key is present, it updates the value. If DName does not have the key, then it inserts the new one with
the given.
>>> da = {'name': 'Kevin', 'age': 25}
# Print Elements
>>> print("Items : ", da)
Items : {'name': 'Kevin', 'age': 25}
# Add an Item
>>> da['job'] = 'Programmer'
>>> print("nItems : ", da)
Items : {'name': 'Kevin', 'age': 25, 'job': 'Programmer’}
# Update an Item
>>> da['name'] = 'Python'
>>> print("nItems : ", da)
Items : {'name': 'Python', 'age': 25, 'job': 'Programmer'}
Methods in Python Dictionary
Functions Description
clear() Removes all Items
copy() Returns Shallow Copy of a Dictionary
fromkeys() Creates a dictionary from the given sequence
get() Find the value of a key
items() Returns view of dictionary’s (key, value) pair
keys() Prints the keys
popitem() Remove the last element of the dictionary
setdefault() Inserts Key With a Value if Key is not Present
pop() Removes and returns element having given key
values() Returns view of all values in the dictionary
update() Updates the Dictionary
Cont..
keys(): The keys() method returns a list of keys in a Python dictionary.
>>> d ={'name': 'Python', 'age': 25, 'job': 'Programmer’}
>>> d.keys()
dict_keys(['name', 'age', 'job'])
values(): The values() method returns a list of values in the dictionary.
>>> d ={'name': 'Python', 'age': 25, 'job': 'Programmer’}
>>> dict4.values()
dict_values(['Python', 25, 'Programmer'])
Cont..
items(): This method returns a list of key-value pairs.
>>> d ={'name': 'Python', 'age': 25, 'job': 'Programmer’}
>>> d.items()
dict_items([('name','Python'),('age',25),('job','Programmer')])
get(): It takes one to two arguments. While the first is the key to search for,
the second is the value to return if the key isn’t found. The default value for
this second argument is None.
>>> d ={'name': 'Python', 'age': 25, 'job': 'Programmer’}
>>> d.get('job')
'Programmer'
>>> d.get("role")
>>> d.get("role","Not Present")
'Not Present'
Cont..
copy(): Python dictionary method copy() returns a shallow copy of the dictionary.
>>> d ={'name': 'Python', 'age': 25, 'job': 'Programmer’}
>>> d2=d.copy()
>>> d
{'name': 'Python', 'age': 25, 'job': 'Programmer’}
>>> d2
{'name': 'Python', 'age': 25, 'job': 'Programmer’}
>>> id(d)
3218144153792
>>> id(d2)
3218150637248
Cont..
pop(): This method is used to remove and display an item from the dictionary. It takes
one or two arguments. The first is the key to be deleted, while the second is the value
that’s returned if the key isn’t found.
>>> d ={'name': 'Python', 'age': 25, 'job': 'Programmer’}
>>> d.pop("age")
25
>>> d
{'name': 'Python', 'job': 'Programmer'}
>>> d.pop("role")
Traceback (most recent call last):
File "<pyshell#31>", line 1, in <module>
d.pop("role")
KeyError: 'role'
>>> d.pop("role",-1)
-1
Cont..
popitem():The popitem() method removes and returns the item that was last inserted into
the dictionary.
>>> d ={'name': 'Python', 'job': 'Programmer’, 'age’: 26}
>>> d.popitem()
('age', 26)
fromkeys(): Python dictionary method fromkeys() creates a new dictionary
with keys from seq and values set to value.
>>> d=fromkeys({1,2,3,4,7},0)
>>> d
{1: 0, 2: 0, 3: 0, 4: 0, 7: 0}
>>> seq = ('name', 'age', ‘job’)
>>> d2 = d2.fromkeys(seq)
>>> d2
{'age': None, 'name': None, ‘job': None}
Cont..
update():The update() method takes another dictionary as an argument. Then it updates
the dictionary to hold values from the other dictionary that it doesn’t already.
>>> d1 ={'name': 'Python', 'job': 'Programmer’}
>>> d2 ={'age’: 26}
>>> d1.update(d2)
>>> print(d1)
{'name': 'python', 'job': 'programmer', 'age': 25}
>>> d1 ={'name': 'Python', 'job': 'Programmer’}
>>> d2 ={'age’: 26, 'name’: ‘Java'}
>>> d1.update(d2)
>>> print(d1)
{'name’: ‘Java', 'job': 'programmer', 'age': 25}
clear(): Removes all elements of dictionary.
>>> d ={'name': 'Python', 'job': 'Programmer’, 'age’: 26}
>>> d.clear()
{}
Cont..
setdefault():
Returns the value of the specified key in the dictionary. If the key not found, then it adds
the key with the specified defaultvalue. If the defaultvalue is not specified then it set None value.
Syntax:
dict.setdefault(key, defaultValue)
Ex:
romanNums = {'I':1, 'II':2, 'III':3}
romanNums.setdefault('IV')
print(romanNums)
{'I': 1, 'II': 2, 'III': 3, 'IV': None}
romanNums.setdefault('VI', 4)
print(romanNums)
{'I': 1, 'II': 2, 'III': 3, 'IV': 4}
Iterating Dictionary
• A dictionary can be iterated using for loop as given below.
# for loop to print all the keys of a dictionary
Employee = {"Name": “Kiran",
"Age": 29,
"salary":25000,
"Company":"GOOGLE"}
for i in Employee:
print(i)
Output:
Name
Age
salary
Company
Iterating Dictionary
# for loop to print all the keys of a dictionary
Employee = {"Name": “Kiran", "Age": 29, "salary":25000,
"Company":"GOOGLE"}
Output:
Kiran
29
25000
GOOGLE
for i in Employee.values():
print(i)
for i in Employee:
print(Employee[i])
Output:
Kiran
29
25000
GOOGLE
Iterating Dictionary
• A dictionary can be iterated using for loop as given below.
# for loop to print all the keys of a dictionary
Employee = {"Name": “Kiran",
"Age": 29,
"salary":25000,
"Company":"GOOGLE"}
for i in Employee.items():
print(i)
Output:
('Name', 'Kiran')
('Age', 29)
('salary', 25000)
('Company',
'GOOGLE')
Difference between List and Dictionary in Python
Comparison
Parameter
List Dictionary
Definition Collection of various elements just like an array.
Collection of elements in the hashed structure as
key-value pairs
Syntax
Placing all the elements inside square brackets [],
separated by commas(,)
Placing all key-value pairs inside curly brackets({}),
separated by a comma. Also, each key and pair is
separated by a semi-colon (:)
Index type Indices are integer values starts from value 0 The keys in the dictionary are of any given data type
Mode of Access We can access the elements using the index value We can access the elements using the keys
Order of
Elements
The default order of elements is always
maintained
No guarantee of maintaining the order
Mutability Lists are mutable in nature
Dictionaries are mutable, but keys do not allow
duplicates
Creation List object is created using list() function Dictionary object is created using dict() function
Sort()
Sort() method sorts the elements in ascending or
descending order
Sort() method sorts the keys in the dictionary by
default
Count()
Count() methods returns the number of elements
appeared in list
Count() method does not exists in dictionation
Reverse() Reverse() method reverse the list elements
Dictionary items cannot be reversed as they are the
key-value pairs
Write a Python program to check whether a given key already exists in a
dictionary.
d = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
key=int(input(“enter key element to be searched”))
if n in d:
print("key present")
else:
print("Key not present")
Write a program to count the number of occurrences of character in a
string.
x = input("Enter a String: ")
count = {}
for ch in x:
count.setdefault(ch, 0)
count[ch] = count[ch] + 1
print(count)
Output:
Enter a String: Kannada
{'K': 1, 'a': 3, 'n': 2, 'd': 1}
Write a Python script to print a dictionary where the keys are numbers
between 1 and 15 (both included) and the values are square of keys.
d=dict()
for x in range(1,16):
d[x]=x**2
print(d)
Output:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49,
8: 64, 9: 81, 10: 100, 11: 121, 12: 144, 13: 169,
14: 196, 15: 225}

More Related Content

Similar to Dictionary in python Dictionary in python Dictionary in pDictionary in python ython (20)

CHAPTER- 9 PYTHON DICTIONARIES.pdf computer science
CHAPTER- 9 PYTHON DICTIONARIES.pdf computer scienceCHAPTER- 9 PYTHON DICTIONARIES.pdf computer science
CHAPTER- 9 PYTHON DICTIONARIES.pdf computer science
Bavish5
 
dictionary14 ppt FINAL.pptx
dictionary14 ppt FINAL.pptxdictionary14 ppt FINAL.pptx
dictionary14 ppt FINAL.pptx
MamtaKaundal1
 
Python Fundamental Data structures: Dictionaries
Python Fundamental Data structures: DictionariesPython Fundamental Data structures: Dictionaries
Python Fundamental Data structures: Dictionaries
KanadamKarteekaPavan1
 
PYTHON Data structures Fundamentals: DICTIONARIES
PYTHON Data structures Fundamentals: DICTIONARIESPYTHON Data structures Fundamentals: DICTIONARIES
PYTHON Data structures Fundamentals: DICTIONARIES
KanadamKarteekaPavan1
 
Python Dictionary concept -R.Chinthamani .pptx
Python Dictionary concept -R.Chinthamani .pptxPython Dictionary concept -R.Chinthamani .pptx
Python Dictionary concept -R.Chinthamani .pptx
SindhuVelmukull
 
Python dictionary
Python dictionaryPython dictionary
Python dictionary
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
Meaning of Dictionary in python language
Meaning of Dictionary in python languageMeaning of Dictionary in python language
Meaning of Dictionary in python language
PRASHANTMISHRA16761
 
Python Dynamic Data type List & Dictionaries
Python Dynamic Data type List & DictionariesPython Dynamic Data type List & Dictionaries
Python Dynamic Data type List & Dictionaries
RuchiNagar3
 
Programming in python Unit-1 Part-1
Programming in python Unit-1 Part-1Programming in python Unit-1 Part-1
Programming in python Unit-1 Part-1
Vikram Nandini
 
Python programming –part 7
Python programming –part 7Python programming –part 7
Python programming –part 7
Megha V
 
Dictionary in python
Dictionary in pythonDictionary in python
Dictionary in python
vikram mahendra
 
Week 10.pptx
Week 10.pptxWeek 10.pptx
Week 10.pptx
CruiseCH
 
DICTIONARIES (1).pptx
DICTIONARIES (1).pptxDICTIONARIES (1).pptx
DICTIONARIES (1).pptx
KalashJain27
 
An Introduction To Python - Dictionaries
An Introduction To Python - DictionariesAn Introduction To Python - Dictionaries
An Introduction To Python - Dictionaries
Blue Elephant Consulting
 
Dictionaries in Python
Dictionaries in PythonDictionaries in Python
Dictionaries in Python
baabtra.com - No. 1 supplier of quality freshers
 
Unit4-Basic Concepts and methods of Dictionary.pptx
Unit4-Basic Concepts and methods of Dictionary.pptxUnit4-Basic Concepts and methods of Dictionary.pptx
Unit4-Basic Concepts and methods of Dictionary.pptx
SwapnaliGawali5
 
Python Programming Essentials - M14 - Dictionaries
Python Programming Essentials - M14 - DictionariesPython Programming Essentials - M14 - Dictionaries
Python Programming Essentials - M14 - Dictionaries
P3 InfoTech Solutions Pvt. Ltd.
 
Dictionary functions and methods.ppt .
Dictionary functions and methods.ppt     .Dictionary functions and methods.ppt     .
Dictionary functions and methods.ppt .
RanjanaMalathi
 
DictionariesPython Programming.One of the datatypes of Python which explains ...
DictionariesPython Programming.One of the datatypes of Python which explains ...DictionariesPython Programming.One of the datatypes of Python which explains ...
DictionariesPython Programming.One of the datatypes of Python which explains ...
kavyamp025
 
Python dictionary
Python   dictionaryPython   dictionary
Python dictionary
Mohammed Sikander
 
CHAPTER- 9 PYTHON DICTIONARIES.pdf computer science
CHAPTER- 9 PYTHON DICTIONARIES.pdf computer scienceCHAPTER- 9 PYTHON DICTIONARIES.pdf computer science
CHAPTER- 9 PYTHON DICTIONARIES.pdf computer science
Bavish5
 
dictionary14 ppt FINAL.pptx
dictionary14 ppt FINAL.pptxdictionary14 ppt FINAL.pptx
dictionary14 ppt FINAL.pptx
MamtaKaundal1
 
Python Fundamental Data structures: Dictionaries
Python Fundamental Data structures: DictionariesPython Fundamental Data structures: Dictionaries
Python Fundamental Data structures: Dictionaries
KanadamKarteekaPavan1
 
PYTHON Data structures Fundamentals: DICTIONARIES
PYTHON Data structures Fundamentals: DICTIONARIESPYTHON Data structures Fundamentals: DICTIONARIES
PYTHON Data structures Fundamentals: DICTIONARIES
KanadamKarteekaPavan1
 
Python Dictionary concept -R.Chinthamani .pptx
Python Dictionary concept -R.Chinthamani .pptxPython Dictionary concept -R.Chinthamani .pptx
Python Dictionary concept -R.Chinthamani .pptx
SindhuVelmukull
 
Meaning of Dictionary in python language
Meaning of Dictionary in python languageMeaning of Dictionary in python language
Meaning of Dictionary in python language
PRASHANTMISHRA16761
 
Python Dynamic Data type List & Dictionaries
Python Dynamic Data type List & DictionariesPython Dynamic Data type List & Dictionaries
Python Dynamic Data type List & Dictionaries
RuchiNagar3
 
Programming in python Unit-1 Part-1
Programming in python Unit-1 Part-1Programming in python Unit-1 Part-1
Programming in python Unit-1 Part-1
Vikram Nandini
 
Python programming –part 7
Python programming –part 7Python programming –part 7
Python programming –part 7
Megha V
 
Week 10.pptx
Week 10.pptxWeek 10.pptx
Week 10.pptx
CruiseCH
 
DICTIONARIES (1).pptx
DICTIONARIES (1).pptxDICTIONARIES (1).pptx
DICTIONARIES (1).pptx
KalashJain27
 
Unit4-Basic Concepts and methods of Dictionary.pptx
Unit4-Basic Concepts and methods of Dictionary.pptxUnit4-Basic Concepts and methods of Dictionary.pptx
Unit4-Basic Concepts and methods of Dictionary.pptx
SwapnaliGawali5
 
Dictionary functions and methods.ppt .
Dictionary functions and methods.ppt     .Dictionary functions and methods.ppt     .
Dictionary functions and methods.ppt .
RanjanaMalathi
 
DictionariesPython Programming.One of the datatypes of Python which explains ...
DictionariesPython Programming.One of the datatypes of Python which explains ...DictionariesPython Programming.One of the datatypes of Python which explains ...
DictionariesPython Programming.One of the datatypes of Python which explains ...
kavyamp025
 

Recently uploaded (20)

chemistry investigatory project for class 12
chemistry investigatory project for class 12chemistry investigatory project for class 12
chemistry investigatory project for class 12
Susis10
 
New Microsoft Office Word Documentfrf.docx
New Microsoft Office Word Documentfrf.docxNew Microsoft Office Word Documentfrf.docx
New Microsoft Office Word Documentfrf.docx
misheetasah
 
David Boutry - Mentors Junior Developers
David Boutry - Mentors Junior DevelopersDavid Boutry - Mentors Junior Developers
David Boutry - Mentors Junior Developers
David Boutry
 
SEW make Brake BE05 – BE30 Brake – Repair Kit
SEW make Brake BE05 – BE30 Brake – Repair KitSEW make Brake BE05 – BE30 Brake – Repair Kit
SEW make Brake BE05 – BE30 Brake – Repair Kit
projectultramechanix
 
22PCOAM16 _ML_Unit 3 Notes & Question bank
22PCOAM16 _ML_Unit 3 Notes & Question bank22PCOAM16 _ML_Unit 3 Notes & Question bank
22PCOAM16 _ML_Unit 3 Notes & Question bank
Guru Nanak Technical Institutions
 
Irja Straus - Beyond Pass and Fail - DevTalks.pdf
Irja Straus - Beyond Pass and Fail - DevTalks.pdfIrja Straus - Beyond Pass and Fail - DevTalks.pdf
Irja Straus - Beyond Pass and Fail - DevTalks.pdf
Irja Straus
 
FINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptx
FINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptxFINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptx
FINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptx
kippcam
 
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODSWIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
samueljackson3773
 
IntroSlides-June-GDG-Cloud-Munich community [email protected]
IntroSlides-June-GDG-Cloud-Munich community gathering@Netlight.pdfIntroSlides-June-GDG-Cloud-Munich community gathering@Netlight.pdf
IntroSlides-June-GDG-Cloud-Munich community [email protected]
Luiz Carneiro
 
02 - Ethics & Professionalism - BEM, IEM, MySET.PPT
02 - Ethics & Professionalism - BEM, IEM, MySET.PPT02 - Ethics & Professionalism - BEM, IEM, MySET.PPT
02 - Ethics & Professionalism - BEM, IEM, MySET.PPT
SharinAbGhani1
 
First Review PPT gfinal gyft ftu liu yrfut go
First Review PPT gfinal gyft  ftu liu yrfut goFirst Review PPT gfinal gyft  ftu liu yrfut go
First Review PPT gfinal gyft ftu liu yrfut go
Sowndarya6
 
IOt Based Research on Challenges and Future
IOt Based Research on Challenges and FutureIOt Based Research on Challenges and Future
IOt Based Research on Challenges and Future
SACHINSAHU821405
 
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) ProjectMontreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Alexandra N. Martinez
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
djiceramil
 
May 2025: Top 10 Read Articles Advanced Information Technology
May 2025: Top 10 Read Articles Advanced Information TechnologyMay 2025: Top 10 Read Articles Advanced Information Technology
May 2025: Top 10 Read Articles Advanced Information Technology
ijait
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
djiceramil
 
The first edition of the AIAG-VDA FMEA.pptx
The first edition of the AIAG-VDA FMEA.pptxThe first edition of the AIAG-VDA FMEA.pptx
The first edition of the AIAG-VDA FMEA.pptx
Mayank Mathur
 
Computer_vision-photometric_image_formation.pdf
Computer_vision-photometric_image_formation.pdfComputer_vision-photometric_image_formation.pdf
Computer_vision-photometric_image_formation.pdf
kumarprem6767merp
 
Research_Sensitization_&_Innovative_Project_Development.pptx
Research_Sensitization_&_Innovative_Project_Development.pptxResearch_Sensitization_&_Innovative_Project_Development.pptx
Research_Sensitization_&_Innovative_Project_Development.pptx
niranjancse
 
社内勉強会資料_Chain of Thought .
社内勉強会資料_Chain of Thought                           .社内勉強会資料_Chain of Thought                           .
社内勉強会資料_Chain of Thought .
NABLAS株式会社
 
chemistry investigatory project for class 12
chemistry investigatory project for class 12chemistry investigatory project for class 12
chemistry investigatory project for class 12
Susis10
 
New Microsoft Office Word Documentfrf.docx
New Microsoft Office Word Documentfrf.docxNew Microsoft Office Word Documentfrf.docx
New Microsoft Office Word Documentfrf.docx
misheetasah
 
David Boutry - Mentors Junior Developers
David Boutry - Mentors Junior DevelopersDavid Boutry - Mentors Junior Developers
David Boutry - Mentors Junior Developers
David Boutry
 
SEW make Brake BE05 – BE30 Brake – Repair Kit
SEW make Brake BE05 – BE30 Brake – Repair KitSEW make Brake BE05 – BE30 Brake – Repair Kit
SEW make Brake BE05 – BE30 Brake – Repair Kit
projectultramechanix
 
Irja Straus - Beyond Pass and Fail - DevTalks.pdf
Irja Straus - Beyond Pass and Fail - DevTalks.pdfIrja Straus - Beyond Pass and Fail - DevTalks.pdf
Irja Straus - Beyond Pass and Fail - DevTalks.pdf
Irja Straus
 
FINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptx
FINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptxFINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptx
FINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptx
kippcam
 
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODSWIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
samueljackson3773
 
02 - Ethics & Professionalism - BEM, IEM, MySET.PPT
02 - Ethics & Professionalism - BEM, IEM, MySET.PPT02 - Ethics & Professionalism - BEM, IEM, MySET.PPT
02 - Ethics & Professionalism - BEM, IEM, MySET.PPT
SharinAbGhani1
 
First Review PPT gfinal gyft ftu liu yrfut go
First Review PPT gfinal gyft  ftu liu yrfut goFirst Review PPT gfinal gyft  ftu liu yrfut go
First Review PPT gfinal gyft ftu liu yrfut go
Sowndarya6
 
IOt Based Research on Challenges and Future
IOt Based Research on Challenges and FutureIOt Based Research on Challenges and Future
IOt Based Research on Challenges and Future
SACHINSAHU821405
 
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) ProjectMontreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Alexandra N. Martinez
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
djiceramil
 
May 2025: Top 10 Read Articles Advanced Information Technology
May 2025: Top 10 Read Articles Advanced Information TechnologyMay 2025: Top 10 Read Articles Advanced Information Technology
May 2025: Top 10 Read Articles Advanced Information Technology
ijait
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
djiceramil
 
The first edition of the AIAG-VDA FMEA.pptx
The first edition of the AIAG-VDA FMEA.pptxThe first edition of the AIAG-VDA FMEA.pptx
The first edition of the AIAG-VDA FMEA.pptx
Mayank Mathur
 
Computer_vision-photometric_image_formation.pdf
Computer_vision-photometric_image_formation.pdfComputer_vision-photometric_image_formation.pdf
Computer_vision-photometric_image_formation.pdf
kumarprem6767merp
 
Research_Sensitization_&_Innovative_Project_Development.pptx
Research_Sensitization_&_Innovative_Project_Development.pptxResearch_Sensitization_&_Innovative_Project_Development.pptx
Research_Sensitization_&_Innovative_Project_Development.pptx
niranjancse
 
社内勉強会資料_Chain of Thought .
社内勉強会資料_Chain of Thought                           .社内勉強会資料_Chain of Thought                           .
社内勉強会資料_Chain of Thought .
NABLAS株式会社
 
Ad

Dictionary in python Dictionary in python Dictionary in pDictionary in python ython

  • 2. What is a Dictionary in Python? • A Dictionary in Python is the unordered, and changeable collection of data values that holds key-value pairs. • Each key-value pair in the dictionary maps the key to its associated value. • Python Dictionary is classified into two elements: Keys and Values. • Keys will be a single element. • Values can be a list or list within a list, numbers, etc.
  • 3. Cont.. • Dictionary is ordered or unordered? • As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered. • When we say that dictionaries are ordered, it means that the items have a defined order, and that order will not change. • Unordered means that the items does not have a defined order, you cannot refer to an item by using an index. • Dictionary is Changeable: • Dictionaries are changeable, meaning that we can change, add or remove items after the dictionary has been created. • Duplicates Not Allowed in dictionary: • Dictionaries cannot have two items with the same key
  • 4. How to Create a Dictionary in Python? • Dictionary is created with curly brackets, inside these curly brackets, keys and values are declared. Each key is separated from its value by a colon (:), while commas separate each element. • A Dictionary in python is declared by enclosing a comma-separated list of key-value pairs using curly braces({}). • Dictionaries are used to store data values in key:value pairs. #Creating an empty dictionary d = {} #Creating an empty dictionary with the dict function d = dict()
  • 5. Cont… # Initializing a dictionary with values a = {"a":1 ,"b":2} b = {'fruit': 'apple', ‘color': ‘red’} c = {'name': ‘Suchith', 'age’: 20} d = {'name': ‘Ishanth’, ‘sem’: [1,2,3,7]} e = {‘branch’:‘CSE’, ‘course’:[‘c’,’java’,’python’]} f = {'a':1, 'b':2, 'c':3, 'd’:2} # For Sequence of Key-Value Pairs g = dict([(1, ‘Apple'), (2, 'Orange'), (3, 'Kiwi')])
  • 6. Properties of Dictionary Keys • Keys must be unique: More than one entry per key is not allowed ( no duplicate key is allowed) • The values in the dictionary can be of any type, while the keys must be immutable like numbers, tuples, or strings. • Dictionary keys are case sensitive- Same key name but with the different cases are treated as different keys in Python dictionaries.
  • 7. How to Access Python Dictionary items? • Since the dictionary is an unordered collection, we can access the values using their keys. • It can be done by placing the key in the square brackets or using the get function. • Ex: Dname[key] or Dname.get(key) • If we access a non-existing one, • The get function returns none. • The key inside a square brackets method throw an error.
  • 8. Cont.. # Accessing dictionary items >>> a = {'name': 'Kevin', 'age': 25, 'job': 'Developer’} # Print >>> print(a) {'name': 'Kevin', 'age': 25, 'job': 'Developer’} >>> print("nName :",a['name’]) Name : Kevin >>> print("Age : ", a['age’]) Age : 25 >>> print("Job : ", a['job’]) Job : Developer
  • 9. Cont.. # Accessing dictionary items >>> a = {'name': 'Kevin', 'age': 25, 'job': 'Developer’} >>> len(a) #length of dictionary 3 # using get() >>> print("Name : ", a.get('name’)) Name : Kevin >>> print("Age : ", a.get('age’)) Age : 25 >>> print("Job : ", a.get('job’)) Job : Developer
  • 10. Insert and Update Dictionary items • Remember, dicts are mutable, so you can insert or update any element at any point in time. Use the below syntax to insert or update values. DName[key] = value • If a key is present, it updates the value. If DName does not have the key, then it inserts the new one with the given. >>> da = {'name': 'Kevin', 'age': 25} # Print Elements >>> print("Items : ", da) Items : {'name': 'Kevin', 'age': 25} # Add an Item >>> da['job'] = 'Programmer' >>> print("nItems : ", da) Items : {'name': 'Kevin', 'age': 25, 'job': 'Programmer’} # Update an Item >>> da['name'] = 'Python' >>> print("nItems : ", da) Items : {'name': 'Python', 'age': 25, 'job': 'Programmer'}
  • 11. Methods in Python Dictionary Functions Description clear() Removes all Items copy() Returns Shallow Copy of a Dictionary fromkeys() Creates a dictionary from the given sequence get() Find the value of a key items() Returns view of dictionary’s (key, value) pair keys() Prints the keys popitem() Remove the last element of the dictionary setdefault() Inserts Key With a Value if Key is not Present pop() Removes and returns element having given key values() Returns view of all values in the dictionary update() Updates the Dictionary
  • 12. Cont.. keys(): The keys() method returns a list of keys in a Python dictionary. >>> d ={'name': 'Python', 'age': 25, 'job': 'Programmer’} >>> d.keys() dict_keys(['name', 'age', 'job']) values(): The values() method returns a list of values in the dictionary. >>> d ={'name': 'Python', 'age': 25, 'job': 'Programmer’} >>> dict4.values() dict_values(['Python', 25, 'Programmer'])
  • 13. Cont.. items(): This method returns a list of key-value pairs. >>> d ={'name': 'Python', 'age': 25, 'job': 'Programmer’} >>> d.items() dict_items([('name','Python'),('age',25),('job','Programmer')]) get(): It takes one to two arguments. While the first is the key to search for, the second is the value to return if the key isn’t found. The default value for this second argument is None. >>> d ={'name': 'Python', 'age': 25, 'job': 'Programmer’} >>> d.get('job') 'Programmer' >>> d.get("role") >>> d.get("role","Not Present") 'Not Present'
  • 14. Cont.. copy(): Python dictionary method copy() returns a shallow copy of the dictionary. >>> d ={'name': 'Python', 'age': 25, 'job': 'Programmer’} >>> d2=d.copy() >>> d {'name': 'Python', 'age': 25, 'job': 'Programmer’} >>> d2 {'name': 'Python', 'age': 25, 'job': 'Programmer’} >>> id(d) 3218144153792 >>> id(d2) 3218150637248
  • 15. Cont.. pop(): This method is used to remove and display an item from the dictionary. It takes one or two arguments. The first is the key to be deleted, while the second is the value that’s returned if the key isn’t found. >>> d ={'name': 'Python', 'age': 25, 'job': 'Programmer’} >>> d.pop("age") 25 >>> d {'name': 'Python', 'job': 'Programmer'} >>> d.pop("role") Traceback (most recent call last): File "<pyshell#31>", line 1, in <module> d.pop("role") KeyError: 'role' >>> d.pop("role",-1) -1
  • 16. Cont.. popitem():The popitem() method removes and returns the item that was last inserted into the dictionary. >>> d ={'name': 'Python', 'job': 'Programmer’, 'age’: 26} >>> d.popitem() ('age', 26) fromkeys(): Python dictionary method fromkeys() creates a new dictionary with keys from seq and values set to value. >>> d=fromkeys({1,2,3,4,7},0) >>> d {1: 0, 2: 0, 3: 0, 4: 0, 7: 0} >>> seq = ('name', 'age', ‘job’) >>> d2 = d2.fromkeys(seq) >>> d2 {'age': None, 'name': None, ‘job': None}
  • 17. Cont.. update():The update() method takes another dictionary as an argument. Then it updates the dictionary to hold values from the other dictionary that it doesn’t already. >>> d1 ={'name': 'Python', 'job': 'Programmer’} >>> d2 ={'age’: 26} >>> d1.update(d2) >>> print(d1) {'name': 'python', 'job': 'programmer', 'age': 25} >>> d1 ={'name': 'Python', 'job': 'Programmer’} >>> d2 ={'age’: 26, 'name’: ‘Java'} >>> d1.update(d2) >>> print(d1) {'name’: ‘Java', 'job': 'programmer', 'age': 25} clear(): Removes all elements of dictionary. >>> d ={'name': 'Python', 'job': 'Programmer’, 'age’: 26} >>> d.clear() {}
  • 18. Cont.. setdefault(): Returns the value of the specified key in the dictionary. If the key not found, then it adds the key with the specified defaultvalue. If the defaultvalue is not specified then it set None value. Syntax: dict.setdefault(key, defaultValue) Ex: romanNums = {'I':1, 'II':2, 'III':3} romanNums.setdefault('IV') print(romanNums) {'I': 1, 'II': 2, 'III': 3, 'IV': None} romanNums.setdefault('VI', 4) print(romanNums) {'I': 1, 'II': 2, 'III': 3, 'IV': 4}
  • 19. Iterating Dictionary • A dictionary can be iterated using for loop as given below. # for loop to print all the keys of a dictionary Employee = {"Name": “Kiran", "Age": 29, "salary":25000, "Company":"GOOGLE"} for i in Employee: print(i) Output: Name Age salary Company
  • 20. Iterating Dictionary # for loop to print all the keys of a dictionary Employee = {"Name": “Kiran", "Age": 29, "salary":25000, "Company":"GOOGLE"} Output: Kiran 29 25000 GOOGLE for i in Employee.values(): print(i) for i in Employee: print(Employee[i]) Output: Kiran 29 25000 GOOGLE
  • 21. Iterating Dictionary • A dictionary can be iterated using for loop as given below. # for loop to print all the keys of a dictionary Employee = {"Name": “Kiran", "Age": 29, "salary":25000, "Company":"GOOGLE"} for i in Employee.items(): print(i) Output: ('Name', 'Kiran') ('Age', 29) ('salary', 25000) ('Company', 'GOOGLE')
  • 22. Difference between List and Dictionary in Python Comparison Parameter List Dictionary Definition Collection of various elements just like an array. Collection of elements in the hashed structure as key-value pairs Syntax Placing all the elements inside square brackets [], separated by commas(,) Placing all key-value pairs inside curly brackets({}), separated by a comma. Also, each key and pair is separated by a semi-colon (:) Index type Indices are integer values starts from value 0 The keys in the dictionary are of any given data type Mode of Access We can access the elements using the index value We can access the elements using the keys Order of Elements The default order of elements is always maintained No guarantee of maintaining the order Mutability Lists are mutable in nature Dictionaries are mutable, but keys do not allow duplicates Creation List object is created using list() function Dictionary object is created using dict() function Sort() Sort() method sorts the elements in ascending or descending order Sort() method sorts the keys in the dictionary by default Count() Count() methods returns the number of elements appeared in list Count() method does not exists in dictionation Reverse() Reverse() method reverse the list elements Dictionary items cannot be reversed as they are the key-value pairs
  • 23. Write a Python program to check whether a given key already exists in a dictionary. d = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60} key=int(input(“enter key element to be searched”)) if n in d: print("key present") else: print("Key not present")
  • 24. Write a program to count the number of occurrences of character in a string. x = input("Enter a String: ") count = {} for ch in x: count.setdefault(ch, 0) count[ch] = count[ch] + 1 print(count) Output: Enter a String: Kannada {'K': 1, 'a': 3, 'n': 2, 'd': 1}
  • 25. Write a Python script to print a dictionary where the keys are numbers between 1 and 15 (both included) and the values are square of keys. d=dict() for x in range(1,16): d[x]=x**2 print(d) Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100, 11: 121, 12: 144, 13: 169, 14: 196, 15: 225}