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}
Ad

More Related Content

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

Python programming –part 7
Python programming –part 7Python programming –part 7
Python programming –part 7
Megha V
 
Python Dictionary concept -R.Chinthamani .pptx
Python Dictionary concept -R.Chinthamani .pptxPython Dictionary concept -R.Chinthamani .pptx
Python Dictionary concept -R.Chinthamani .pptx
SindhuVelmukull
 
PE1 Module 4.ppt
PE1 Module 4.pptPE1 Module 4.ppt
PE1 Module 4.ppt
balewayalew
 
Python Dynamic Data type List & Dictionaries
Python Dynamic Data type List & DictionariesPython Dynamic Data type List & Dictionaries
Python Dynamic Data type List & Dictionaries
RuchiNagar3
 
Using-Python-Libraries.9485146.powerpoint.pptx
Using-Python-Libraries.9485146.powerpoint.pptxUsing-Python-Libraries.9485146.powerpoint.pptx
Using-Python-Libraries.9485146.powerpoint.pptx
UadAccount
 
CS101- Introduction to Computing- Lecture 29
CS101- Introduction to Computing- Lecture 29CS101- Introduction to Computing- Lecture 29
CS101- Introduction to Computing- Lecture 29
Bilal Ahmed
 
Dictionaries in python
Dictionaries in pythonDictionaries in python
Dictionaries in python
JayanthiNeelampalli
 
Pytho dictionaries
Pytho dictionaries Pytho dictionaries
Pytho dictionaries
BMS Institute of Technology and Management
 
CHAPTER 01 FUNCTION in python class 12th.pptx
CHAPTER 01 FUNCTION in python class 12th.pptxCHAPTER 01 FUNCTION in python class 12th.pptx
CHAPTER 01 FUNCTION in python class 12th.pptx
PreeTVithule1
 
UNIT 1 - Revision of Basics - II.pptx
UNIT 1 - Revision of Basics - II.pptxUNIT 1 - Revision of Basics - II.pptx
UNIT 1 - Revision of Basics - II.pptx
NishanSidhu2
 
Python list tuple dictionary .pptx
Python list tuple dictionary       .pptxPython list tuple dictionary       .pptx
Python list tuple dictionary .pptx
miteshchaudhari4466
 
Python Lecture 10
Python Lecture 10Python Lecture 10
Python Lecture 10
Inzamam Baig
 
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
 
dictionary14 ppt FINAL.pptx
dictionary14 ppt FINAL.pptxdictionary14 ppt FINAL.pptx
dictionary14 ppt FINAL.pptx
MamtaKaundal1
 
chap 06 hgjhg hghg hh ghg jh jhghj gj g.ppt
chap 06 hgjhg  hghg hh ghg jh jhghj gj g.pptchap 06 hgjhg  hghg hh ghg jh jhghj gj g.ppt
chap 06 hgjhg hghg hh ghg jh jhghj gj g.ppt
santonino3
 
beginners_python_cheat_sheet_pcc_all_bw.pdf
beginners_python_cheat_sheet_pcc_all_bw.pdfbeginners_python_cheat_sheet_pcc_all_bw.pdf
beginners_python_cheat_sheet_pcc_all_bw.pdf
GuarachandarChand
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
baabtra.com - No. 1 supplier of quality freshers
 
CSV JSON and XML files in Python.pptx
CSV JSON and XML files in Python.pptxCSV JSON and XML files in Python.pptx
CSV JSON and XML files in Python.pptx
Ramakrishna Reddy Bijjam
 
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
S.Mohideen Badhusha
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
Utkarsh Sengar
 
Python programming –part 7
Python programming –part 7Python programming –part 7
Python programming –part 7
Megha V
 
Python Dictionary concept -R.Chinthamani .pptx
Python Dictionary concept -R.Chinthamani .pptxPython Dictionary concept -R.Chinthamani .pptx
Python Dictionary concept -R.Chinthamani .pptx
SindhuVelmukull
 
PE1 Module 4.ppt
PE1 Module 4.pptPE1 Module 4.ppt
PE1 Module 4.ppt
balewayalew
 
Python Dynamic Data type List & Dictionaries
Python Dynamic Data type List & DictionariesPython Dynamic Data type List & Dictionaries
Python Dynamic Data type List & Dictionaries
RuchiNagar3
 
Using-Python-Libraries.9485146.powerpoint.pptx
Using-Python-Libraries.9485146.powerpoint.pptxUsing-Python-Libraries.9485146.powerpoint.pptx
Using-Python-Libraries.9485146.powerpoint.pptx
UadAccount
 
CS101- Introduction to Computing- Lecture 29
CS101- Introduction to Computing- Lecture 29CS101- Introduction to Computing- Lecture 29
CS101- Introduction to Computing- Lecture 29
Bilal Ahmed
 
CHAPTER 01 FUNCTION in python class 12th.pptx
CHAPTER 01 FUNCTION in python class 12th.pptxCHAPTER 01 FUNCTION in python class 12th.pptx
CHAPTER 01 FUNCTION in python class 12th.pptx
PreeTVithule1
 
UNIT 1 - Revision of Basics - II.pptx
UNIT 1 - Revision of Basics - II.pptxUNIT 1 - Revision of Basics - II.pptx
UNIT 1 - Revision of Basics - II.pptx
NishanSidhu2
 
Python list tuple dictionary .pptx
Python list tuple dictionary       .pptxPython list tuple dictionary       .pptx
Python list tuple dictionary .pptx
miteshchaudhari4466
 
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
 
dictionary14 ppt FINAL.pptx
dictionary14 ppt FINAL.pptxdictionary14 ppt FINAL.pptx
dictionary14 ppt FINAL.pptx
MamtaKaundal1
 
chap 06 hgjhg hghg hh ghg jh jhghj gj g.ppt
chap 06 hgjhg  hghg hh ghg jh jhghj gj g.pptchap 06 hgjhg  hghg hh ghg jh jhghj gj g.ppt
chap 06 hgjhg hghg hh ghg jh jhghj gj g.ppt
santonino3
 
beginners_python_cheat_sheet_pcc_all_bw.pdf
beginners_python_cheat_sheet_pcc_all_bw.pdfbeginners_python_cheat_sheet_pcc_all_bw.pdf
beginners_python_cheat_sheet_pcc_all_bw.pdf
GuarachandarChand
 
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
S.Mohideen Badhusha
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
Utkarsh Sengar
 

Recently uploaded (20)

DSP and MV the Color image processing.ppt
DSP and MV the  Color image processing.pptDSP and MV the  Color image processing.ppt
DSP and MV the Color image processing.ppt
HafizAhamed8
 
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G..."Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
Infopitaara
 
Resistance measurement and cfd test on darpa subboff model
Resistance measurement and cfd test on darpa subboff modelResistance measurement and cfd test on darpa subboff model
Resistance measurement and cfd test on darpa subboff model
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
 
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E..."Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
Infopitaara
 
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design ThinkingDT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DhruvChotaliya2
 
Smart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineeringSmart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineering
rushikeshnavghare94
 
The Gaussian Process Modeling Module in UQLab
The Gaussian Process Modeling Module in UQLabThe Gaussian Process Modeling Module in UQLab
The Gaussian Process Modeling Module in UQLab
Journal of Soft Computing in Civil Engineering
 
15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...
IJCSES Journal
 
new ppt artificial intelligence historyyy
new ppt artificial intelligence historyyynew ppt artificial intelligence historyyy
new ppt artificial intelligence historyyy
PianoPianist
 
Data Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptxData Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptx
RushaliDeshmukh2
 
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Journal of Soft Computing in Civil Engineering
 
some basics electrical and electronics knowledge
some basics electrical and electronics knowledgesome basics electrical and electronics knowledge
some basics electrical and electronics knowledge
nguyentrungdo88
 
LECTURE-16 EARTHEN DAM - II.pptx it's uses
LECTURE-16 EARTHEN DAM - II.pptx it's usesLECTURE-16 EARTHEN DAM - II.pptx it's uses
LECTURE-16 EARTHEN DAM - II.pptx it's uses
CLokeshBehera123
 
Introduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptxIntroduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptx
AS1920
 
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
charlesdick1345
 
Compiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptxCompiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptx
RushaliDeshmukh2
 
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdffive-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
AdityaSharma944496
 
Data Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptxData Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptx
RushaliDeshmukh2
 
Metal alkyne complexes.pptx in chemistry
Metal alkyne complexes.pptx in chemistryMetal alkyne complexes.pptx in chemistry
Metal alkyne complexes.pptx in chemistry
mee23nu
 
Introduction to FLUID MECHANICS & KINEMATICS
Introduction to FLUID MECHANICS &  KINEMATICSIntroduction to FLUID MECHANICS &  KINEMATICS
Introduction to FLUID MECHANICS & KINEMATICS
narayanaswamygdas
 
DSP and MV the Color image processing.ppt
DSP and MV the  Color image processing.pptDSP and MV the  Color image processing.ppt
DSP and MV the Color image processing.ppt
HafizAhamed8
 
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G..."Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
Infopitaara
 
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E..."Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
Infopitaara
 
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design ThinkingDT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DhruvChotaliya2
 
Smart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineeringSmart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineering
rushikeshnavghare94
 
15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...
IJCSES Journal
 
new ppt artificial intelligence historyyy
new ppt artificial intelligence historyyynew ppt artificial intelligence historyyy
new ppt artificial intelligence historyyy
PianoPianist
 
Data Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptxData Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptx
RushaliDeshmukh2
 
some basics electrical and electronics knowledge
some basics electrical and electronics knowledgesome basics electrical and electronics knowledge
some basics electrical and electronics knowledge
nguyentrungdo88
 
LECTURE-16 EARTHEN DAM - II.pptx it's uses
LECTURE-16 EARTHEN DAM - II.pptx it's usesLECTURE-16 EARTHEN DAM - II.pptx it's uses
LECTURE-16 EARTHEN DAM - II.pptx it's uses
CLokeshBehera123
 
Introduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptxIntroduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptx
AS1920
 
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
charlesdick1345
 
Compiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptxCompiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptx
RushaliDeshmukh2
 
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdffive-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
AdityaSharma944496
 
Data Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptxData Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptx
RushaliDeshmukh2
 
Metal alkyne complexes.pptx in chemistry
Metal alkyne complexes.pptx in chemistryMetal alkyne complexes.pptx in chemistry
Metal alkyne complexes.pptx in chemistry
mee23nu
 
Introduction to FLUID MECHANICS & KINEMATICS
Introduction to FLUID MECHANICS &  KINEMATICSIntroduction to FLUID MECHANICS &  KINEMATICS
Introduction to FLUID MECHANICS & KINEMATICS
narayanaswamygdas
 
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}