SlideShare a Scribd company logo
Introduction to
Dictionaries
• Pair of items
• Each pair has key and value
• Keys should be unique
• Key and value are separated
by :
• Each pair is separated by ,
Example:
dict = {‘Alice’ : 1234, ‘Bob’ :
Properties of
Dictionaries
• Unordered mutable collections
• Items are stored and fetched by key
• Accessed by key, not offset position
• Unordered collections of arbitrary objects
• Variable-length, heterogeneous, and arbitrarily
nestable
Creating a
Dictionary
Creating an EMPTY
dictionary
dictname =
{}
Example:
Dict1 = {}
MyDict =
{} Books
= {}
Creating a dictionary with
items
dictname = {key1:val1,
key2:val2, ….}
Example:
MyDict = { 1 : ‘Chocolate’, 2 : ‘Icecream’}
MyCourse = {‘MS’ : ‘Python’, ‘IT’ : ‘C’, ‘CSE’ : ‘C++’, ‘MCA’ :
‘Java’}
MyCircle = {‘Hubby’:9486028245, ‘Mom’:9486301601}
Accessing
Values
Using keys within square
brackets
>>> print MyDict[1]
‘Chocolate’
>>> print MyCourse[‘CSE’]
‘C++’
Updating
Elements
• Update by adding a new item (key-
value) pair
• Modify an existing entry
>>> MyDict[1] = ‘Pizza’
>>> MyCourse[‘MCA’] = ‘UML’
Deleting
Elements
• remove an element in a dictionary using
the key
>>> del MyCourse[‘IT’]
• remove all the elements
>>> MyCourse.clear()
• delete the dictionary
>>> del MyCourse
Basic
Operations
>>> D = {'spam': 2, 'ham': 1,
'eggs': 3}
>>>
len(D)
# Number of entries in
dictionary 3
>>> 'ham' in
D
# Key membership
test
Tru
e
>>>
list(D.keys())
# Create a new list of D's
keys
['eggs', 'spam',
'ham']
Basic
Operations
# A key that is
there
# A key that is
missing
>>> list(D.values())
[3, 2, 1]
>>> list(D.items())
[('eggs', 3), ('spam', 2),
('ham', 1)]
>>> D.get('spam')
2
>>> print(D.get('toast'))
None
Update
Method
>>> D
{'eggs': 3, 'spam': 2,
'ham': 1}
>>> D2 = {'toast':4,
'muffin':5}
>>> D.update(D2)
>>> D
{'eggs': 3, 'muffin': 5, 'toast': 4, 'spam': 2,
'ham': 1}
#unordere
d
POP
Method
Delete and return value for a given key
>>> D = {'eggs': 3, 'muffin': 5, 'toast': 4, 'spam': 2,
'ham': 1}
>>> D.pop('muffin')
5
>>> D.pop('toast‘)
4
>>> D
{'eggs': 3, 'spam': 2, 'ham': 1}
List vs
Dictionary
>>> L =
[]
>>> L[99] =
'spam’
IndexError: list assignment index out of
range
>>>D = {}
>>> D[99] =
'spam'
>>> D[99]
'spam'
>>> D {99:
Nesting in
dictionaries
>>> jobs = []
>>>
jobs.append('developer')
>>>
jobs.append(‘manager‘)
# jobs = [‘developer’,
‘manager’]
rec = {}
>>> rec['name'] = 'Bob'
>>> rec['age'] = 40
>>> rec['job'] = jobs
>>> rec
{'name': 'Bob', 'age': 40, 'job': ['developer',
'manager']}
>>> rec['name']
'Bob'
>>> rec['job']
['developer',
'manager']
>>> rec['job'][1]
'manager’
Other Ways to Make
Dictionaries
D = {'name': 'Bob', 'age':
40}
D =
{}
# Assign by keys
dynamically
D['name'] = 'Bob'
D['age'] = 40
# Creating a dictionary by
assignment
dict(name='Bob', age=40)
# Creating dictionary with tuples
form dict([('name', 'Bob'), ('age',
Comprehensions in
Dictionaries
>>> D = {k: v for (k, v) in zip(['a', 'b', 'c'], [1,
2, 3])}
>>> D
{'a': 1, 'b': 2, 'c': 3}
>>> D = {x: x ** 2 for x in [1, 2, 3, 4]}
>>> D
{1: 1, 2: 4, 3: 9, 4: 16}
>>> D = {c: c * 4 for c in 'SPAM'}
>>> D
{'S': 'SSSS', 'P': 'PPPP', 'A': 'AAAA', 'M': 'MMMM'}
>>> D = {c.lower(): c + '!' for c in ['SPAM', 'EGGS',
'HAM']}
>>> D
{'eggs': 'EGGS!', 'spam': 'SPAM!', 'ham': 'HAM!'}
Initializing
Dictionaries
# Initialize dict from keys
>>> D = dict.fromkeys(['a', 'b',
'c'], 0)
>>> D
{'a': 0,'b': 0, 'c': 0}
# Same, but with a
comprehension
>>> D = {k:0 for k in ['a', 'b', 'c']}
>>> D
>>> D = {k: None for k in 'spam'}
>>> D {'s': None, 'p': None, 'a': None, 'm': None}
Dictionary methods
<dict>.items()
displays the items in the dictionary (pair of keys and
values)
<dict>.keys()
display the keys in the dictionary
<dict>.values()
<dict>.pop()
removes the last item from the dictionary
<dict2> = <dict1>.copy()
copies the items from dict1 to dict2
<dict>.clear()
removes all the items from the dictionary
str(dict)
produces printable string representation of a
dictionary
len(dict)
returns the number of items in the dictionary
Dictionaries can replace elif
ladder/switch-case
print ({1:’one’,2:’two’,3:’three’,4:’four’,5:’five’}
[choice]) if choice = 3 then the code prints
three
python advanced data structure dictionary with examples python advanced data structure dictionary with examples
2
5
2
6
Exercise 1: Convert two lists into a dictionary.
Exercise 2: Merge two Python dictionaries into one.
Exercise 3: Create a dictionary by extracting the keys from a given
dictionary.
Exercise 4: Delete a list of keys from a dictionary.
Exercise 5: Check if a value exists in a dictionary.
Exercise 6: Rename key of a dictionary.
Exercise 7: Write a Python program to sum all the items in a dictionary.
Exercise 8: Write a Python program to sort a given dictionary by key.
Exercise 9: Write a Python program to get the maximum and minimum
value in a dictionary.

More Related Content

PPT
2 UNIT CH3 Dictionaries v1.ppt
tocidfh
 
PPTX
Dictionary in python Dictionary in python Dictionary in pDictionary in python...
sumanthcmcse
 
PDF
Python Dictionary
Soba Arjun
 
PPTX
Dictionaries.pptx
akshat205573
 
PPTX
Farhana shaikh webinar_dictionaries
Farhana Shaikh
 
PPTX
Meaning of Dictionary in python language
PRASHANTMISHRA16761
 
PDF
Lecture-6.pdf
Bhavya103897
 
PPTX
Python list tuple dictionary .pptx
miteshchaudhari4466
 
2 UNIT CH3 Dictionaries v1.ppt
tocidfh
 
Dictionary in python Dictionary in python Dictionary in pDictionary in python...
sumanthcmcse
 
Python Dictionary
Soba Arjun
 
Dictionaries.pptx
akshat205573
 
Farhana shaikh webinar_dictionaries
Farhana Shaikh
 
Meaning of Dictionary in python language
PRASHANTMISHRA16761
 
Lecture-6.pdf
Bhavya103897
 
Python list tuple dictionary .pptx
miteshchaudhari4466
 

Similar to python advanced data structure dictionary with examples python advanced data structure dictionary with examples (20)

PPTX
Python-Dictionaries.pptx easy way to learn dictionaries
panchalneha692
 
PDF
Python dictionaries
Krishna Nanda
 
PPT
ComandosDePython_ComponentesBasicosImpl.ppt
oscarJulianPerdomoCh1
 
PPTX
python chapter 1
Raghu nath
 
PPTX
Python chapter 2
Raghu nath
 
PDF
Beautiful python - PyLadies
Alicia Pérez
 
PDF
Python Variable Types, List, Tuple, Dictionary
Soba Arjun
 
PDF
Python_Cheat_Sheet_Keywords_1664634397.pdf
sagar414433
 
PDF
Python_Cheat_Sheet_Keywords_1664634397.pdf
sagar414433
 
PPTX
UNIT 1 - Revision of Basics - II.pptx
NishanSidhu2
 
PPTX
An Introduction to Tuple List Dictionary in Python
yashar Aliabasi
 
PPTX
Ch_13_Dictionary.pptx
HarishParthasarathy4
 
PDF
An overview of Python 2.7
decoupled
 
PDF
A tour of Python
Aleksandar Veselinovic
 
PPTX
Python - Data Structures
NR Computer Learning Center
 
PDF
Programming in python Unit-1 Part-1
Vikram Nandini
 
PPTX
dictionary14 ppt FINAL.pptx
MamtaKaundal1
 
PDF
Ruby 2: some new things
David Black
 
PPTX
Ggplot2 v3
Josh Doyle
 
Python-Dictionaries.pptx easy way to learn dictionaries
panchalneha692
 
Python dictionaries
Krishna Nanda
 
ComandosDePython_ComponentesBasicosImpl.ppt
oscarJulianPerdomoCh1
 
python chapter 1
Raghu nath
 
Python chapter 2
Raghu nath
 
Beautiful python - PyLadies
Alicia Pérez
 
Python Variable Types, List, Tuple, Dictionary
Soba Arjun
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
sagar414433
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
sagar414433
 
UNIT 1 - Revision of Basics - II.pptx
NishanSidhu2
 
An Introduction to Tuple List Dictionary in Python
yashar Aliabasi
 
Ch_13_Dictionary.pptx
HarishParthasarathy4
 
An overview of Python 2.7
decoupled
 
A tour of Python
Aleksandar Veselinovic
 
Python - Data Structures
NR Computer Learning Center
 
Programming in python Unit-1 Part-1
Vikram Nandini
 
dictionary14 ppt FINAL.pptx
MamtaKaundal1
 
Ruby 2: some new things
David Black
 
Ggplot2 v3
Josh Doyle
 
Ad

Recently uploaded (20)

PDF
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
PDF
Get More from Fiori Automation - What’s New, What Works, and What’s Next.pdf
Precisely
 
PDF
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
PDF
Software Development Methodologies in 2025
KodekX
 
PDF
MASTERDECK GRAPHSUMMIT SYDNEY (Public).pdf
Neo4j
 
PDF
The Future of Artificial Intelligence (AI)
Mukul
 
PDF
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
PDF
OFFOFFBOX™ – A New Era for African Film | Startup Presentation
ambaicciwalkerbrian
 
PDF
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
PPTX
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
PPTX
Dev Dives: Automate, test, and deploy in one place—with Unified Developer Exp...
AndreeaTom
 
PDF
Responsible AI and AI Ethics - By Sylvester Ebhonu
Sylvester Ebhonu
 
PDF
Event Presentation Google Cloud Next Extended 2025
minhtrietgect
 
PDF
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
PPTX
AI in Daily Life: How Artificial Intelligence Helps Us Every Day
vanshrpatil7
 
PDF
Make GenAI investments go further with the Dell AI Factory
Principled Technologies
 
PDF
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
Artjoker Software Development Company
 
PDF
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
 
PDF
Trying to figure out MCP by actually building an app from scratch with open s...
Julien SIMON
 
PPTX
IT Runs Better with ThousandEyes AI-driven Assurance
ThousandEyes
 
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
Get More from Fiori Automation - What’s New, What Works, and What’s Next.pdf
Precisely
 
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
Software Development Methodologies in 2025
KodekX
 
MASTERDECK GRAPHSUMMIT SYDNEY (Public).pdf
Neo4j
 
The Future of Artificial Intelligence (AI)
Mukul
 
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
OFFOFFBOX™ – A New Era for African Film | Startup Presentation
ambaicciwalkerbrian
 
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
Dev Dives: Automate, test, and deploy in one place—with Unified Developer Exp...
AndreeaTom
 
Responsible AI and AI Ethics - By Sylvester Ebhonu
Sylvester Ebhonu
 
Event Presentation Google Cloud Next Extended 2025
minhtrietgect
 
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
AI in Daily Life: How Artificial Intelligence Helps Us Every Day
vanshrpatil7
 
Make GenAI investments go further with the Dell AI Factory
Principled Technologies
 
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
Artjoker Software Development Company
 
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
 
Trying to figure out MCP by actually building an app from scratch with open s...
Julien SIMON
 
IT Runs Better with ThousandEyes AI-driven Assurance
ThousandEyes
 
Ad

python advanced data structure dictionary with examples python advanced data structure dictionary with examples

  • 1. Introduction to Dictionaries • Pair of items • Each pair has key and value • Keys should be unique • Key and value are separated by : • Each pair is separated by , Example: dict = {‘Alice’ : 1234, ‘Bob’ :
  • 2. Properties of Dictionaries • Unordered mutable collections • Items are stored and fetched by key • Accessed by key, not offset position • Unordered collections of arbitrary objects • Variable-length, heterogeneous, and arbitrarily nestable
  • 3. Creating a Dictionary Creating an EMPTY dictionary dictname = {} Example: Dict1 = {} MyDict = {} Books = {} Creating a dictionary with items dictname = {key1:val1, key2:val2, ….} Example: MyDict = { 1 : ‘Chocolate’, 2 : ‘Icecream’} MyCourse = {‘MS’ : ‘Python’, ‘IT’ : ‘C’, ‘CSE’ : ‘C++’, ‘MCA’ : ‘Java’} MyCircle = {‘Hubby’:9486028245, ‘Mom’:9486301601}
  • 4. Accessing Values Using keys within square brackets >>> print MyDict[1] ‘Chocolate’ >>> print MyCourse[‘CSE’] ‘C++’
  • 5. Updating Elements • Update by adding a new item (key- value) pair • Modify an existing entry >>> MyDict[1] = ‘Pizza’ >>> MyCourse[‘MCA’] = ‘UML’
  • 6. Deleting Elements • remove an element in a dictionary using the key >>> del MyCourse[‘IT’] • remove all the elements >>> MyCourse.clear() • delete the dictionary >>> del MyCourse
  • 7. Basic Operations >>> D = {'spam': 2, 'ham': 1, 'eggs': 3} >>> len(D) # Number of entries in dictionary 3 >>> 'ham' in D # Key membership test Tru e >>> list(D.keys()) # Create a new list of D's keys ['eggs', 'spam', 'ham']
  • 8. Basic Operations # A key that is there # A key that is missing >>> list(D.values()) [3, 2, 1] >>> list(D.items()) [('eggs', 3), ('spam', 2), ('ham', 1)] >>> D.get('spam') 2 >>> print(D.get('toast')) None
  • 9. Update Method >>> D {'eggs': 3, 'spam': 2, 'ham': 1} >>> D2 = {'toast':4, 'muffin':5} >>> D.update(D2) >>> D {'eggs': 3, 'muffin': 5, 'toast': 4, 'spam': 2, 'ham': 1} #unordere d
  • 10. POP Method Delete and return value for a given key >>> D = {'eggs': 3, 'muffin': 5, 'toast': 4, 'spam': 2, 'ham': 1} >>> D.pop('muffin') 5 >>> D.pop('toast‘) 4 >>> D {'eggs': 3, 'spam': 2, 'ham': 1}
  • 11. List vs Dictionary >>> L = [] >>> L[99] = 'spam’ IndexError: list assignment index out of range >>>D = {} >>> D[99] = 'spam' >>> D[99] 'spam' >>> D {99:
  • 12. Nesting in dictionaries >>> jobs = [] >>> jobs.append('developer') >>> jobs.append(‘manager‘) # jobs = [‘developer’, ‘manager’] rec = {} >>> rec['name'] = 'Bob' >>> rec['age'] = 40 >>> rec['job'] = jobs >>> rec {'name': 'Bob', 'age': 40, 'job': ['developer', 'manager']}
  • 14. Other Ways to Make Dictionaries D = {'name': 'Bob', 'age': 40} D = {} # Assign by keys dynamically D['name'] = 'Bob' D['age'] = 40 # Creating a dictionary by assignment dict(name='Bob', age=40) # Creating dictionary with tuples form dict([('name', 'Bob'), ('age',
  • 15. Comprehensions in Dictionaries >>> D = {k: v for (k, v) in zip(['a', 'b', 'c'], [1, 2, 3])} >>> D {'a': 1, 'b': 2, 'c': 3} >>> D = {x: x ** 2 for x in [1, 2, 3, 4]} >>> D {1: 1, 2: 4, 3: 9, 4: 16}
  • 16. >>> D = {c: c * 4 for c in 'SPAM'} >>> D {'S': 'SSSS', 'P': 'PPPP', 'A': 'AAAA', 'M': 'MMMM'} >>> D = {c.lower(): c + '!' for c in ['SPAM', 'EGGS', 'HAM']} >>> D {'eggs': 'EGGS!', 'spam': 'SPAM!', 'ham': 'HAM!'}
  • 17. Initializing Dictionaries # Initialize dict from keys >>> D = dict.fromkeys(['a', 'b', 'c'], 0) >>> D {'a': 0,'b': 0, 'c': 0} # Same, but with a comprehension >>> D = {k:0 for k in ['a', 'b', 'c']} >>> D
  • 18. >>> D = {k: None for k in 'spam'} >>> D {'s': None, 'p': None, 'a': None, 'm': None} Dictionary methods <dict>.items() displays the items in the dictionary (pair of keys and values) <dict>.keys() display the keys in the dictionary <dict>.values()
  • 19. <dict>.pop() removes the last item from the dictionary <dict2> = <dict1>.copy() copies the items from dict1 to dict2 <dict>.clear() removes all the items from the dictionary str(dict) produces printable string representation of a dictionary len(dict) returns the number of items in the dictionary
  • 20. Dictionaries can replace elif ladder/switch-case print ({1:’one’,2:’two’,3:’three’,4:’four’,5:’five’} [choice]) if choice = 3 then the code prints three
  • 22. 2 5
  • 23. 2 6
  • 24. Exercise 1: Convert two lists into a dictionary. Exercise 2: Merge two Python dictionaries into one. Exercise 3: Create a dictionary by extracting the keys from a given dictionary. Exercise 4: Delete a list of keys from a dictionary. Exercise 5: Check if a value exists in a dictionary. Exercise 6: Rename key of a dictionary. Exercise 7: Write a Python program to sum all the items in a dictionary. Exercise 8: Write a Python program to sort a given dictionary by key. Exercise 9: Write a Python program to get the maximum and minimum value in a dictionary.