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
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.

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

  • 1.
    Introduction to Dictionaries • Pairof 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 • Unorderedmutable 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 anEMPTY 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 withinsquare brackets >>> print MyDict[1] ‘Chocolate’ >>> print MyCourse[‘CSE’] ‘C++’
  • 5.
    Updating Elements • Update byadding a new item (key- value) pair • Modify an existing entry >>> MyDict[1] = ‘Pizza’ >>> MyCourse[‘MCA’] = ‘UML’
  • 6.
    Deleting Elements • remove anelement 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 keythat 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 returnvalue 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']}
  • 13.
  • 14.
    Other Ways toMake 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 dictfrom 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 lastitem 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 replaceelif ladder/switch-case print ({1:’one’,2:’two’,3:’three’,4:’four’,5:’five’} [choice]) if choice = 3 then the code prints three
  • 22.
  • 23.
  • 24.
    Exercise 1: Converttwo 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.