Introduction to Dictionary

Important points

  • It is a collection of key-value pairs
  • we can use any immutable type as a dictionary key - string, integer, float, Boolean, tuples etc. A list nor dictionary cannot be a dictionary key because they are mutable
  • Dictionary does not support integer indexing like a list. They are indexed by keys
  • Duplicate keys are not allowed
  • Duplicate values are allowed

Creating Dictionaries

# Create a dictionary
ipl_team_cities = {
    "Chennai Super Kings": "Chennai",
    "Delhi Capitals": "Delhi",
    "Kings XI Punjab": "Mohali",
    "Kolkata Knight Riders": "Kolkata",
    "Mumbai Indians": "Mumbai",
    "Rajasthan Royals": "Jaipur",
    "Royal Challengers Bangalore": "Bangalore",
    "Sunrisers Hyderabad": "Hyderabad"
}
# Create a dictionary with 'dict()' function
# The input to dict should be a sequence of key-value pairs
# A list of tuples works as input
ipl_teams = dict([("Chennai Super Kings", "Chennai"),
                    ("Delhi Capitals", "Delhi"),    
                    ("Kings XI Punjab", "Mohali"),    
                    ("Kolkata Knight Riders", "Kolkata"),    
                    ("Mumbai Indians", "Mumbai"),    
                    ("Rajasthan Royals", "Jaipur"),    
                    ("Royal Challengers Bangalore", "Bangalore"),    
                    ("Sunrisers Hyderabad", "Hyderabad")])

Accessing Dictionary Values

ipl_teams['Mumbai Indians']
'Mumbai'
# Refering a key which is not in the dictionary will raise keyError
ipl_teams['Pune Rockers']
KeyError: 'Pune Rockers'
ipl_teams_nested = {
    "Chennai Super Kings": {
        "city": "Chennai",
        "owner": "Chennai Super Kings Cricket Ltd",
        "coach": "Stephen Fleming",
        "captain": "MS Dhoni",
        "home_ground": "M. A. Chidambaram Stadium"
    },
    "Delhi Capitals": {
        "city": "Delhi",
        "owner": "GMR Group and JSW Group",
        "coach": "Ricky Ponting",
        "captain": "Rishabh Pant",
        "home_ground": "Arun Jaitley Stadium"
    }
}
# Accessing the values from the nested dictionary
ipl_teams_nested['Chennai Super Kings']['city']
'Chennai'

Updating Dictionary values

# Adding a value to the dictionary
ipl_teams['Pune Rockers'] = 'pune'
ipl_teams
{'Chennai Super Kings': 'Chennai',
 'Delhi Capitals': 'Delhi',
 'Kings XI Punjab': 'Mohali',
 'Kolkata Knight Riders': 'Kolkata',
 'Mumbai Indians': 'Mumbai',
 'Rajasthan Royals': 'Jaipur',
 'Royal Challengers Bangalore': 'Bangalore',
 'Sunrisers Hyderabad': 'Hyderabad',
 'Pune Rockers': 'pune'}
# Updating a value in the dictionary
ipl_teams['Pune Rockers'] = 'Pune'
ipl_teams
{'Chennai Super Kings': 'Chennai',
 'Delhi Capitals': 'Delhi',
 'Kings XI Punjab': 'Mohali',
 'Kolkata Knight Riders': 'Kolkata',
 'Mumbai Indians': 'Mumbai',
 'Rajasthan Royals': 'Jaipur',
 'Royal Challengers Bangalore': 'Bangalore',
 'Sunrisers Hyderabad': 'Hyderabad',
 'Pune Rockers': 'Pune'}
# delete a key 
del ipl_teams['Pune Rockers']
ipl_teams
{'Chennai Super Kings': 'Chennai',
 'Delhi Capitals': 'Delhi',
 'Kings XI Punjab': 'Mohali',
 'Kolkata Knight Riders': 'Kolkata',
 'Mumbai Indians': 'Mumbai',
 'Rajasthan Royals': 'Jaipur',
 'Royal Challengers Bangalore': 'Bangalore',
 'Sunrisers Hyderabad': 'Hyderabad'}

Operators and Built-in Functions

# check if a key is present in a dictionary
'Delhi Capitals' in ipl_teams
True
'Pune Rockers' not in ipl_teams
True
len(ipl_teams)
8

Dictionary Methods

# clear the dictionary
ipl_team_cities.clear()
ipl_team_cities
{}
# Access a value from a dictionary
ipl_teams.get('Chennai Super Kings')
'Chennai'
# If the key is not present in the dictionary, it will return None
ipl_teams.get('chennai Super Kings')
# Returns default value instead of None if the key is not present
ipl_teams.get('chennai Super Kings', -1) # -1 is the default value here
-1
# Return a list of key-value paris in the dictionary
ipl_teams.items()
dict_items([('Chennai Super Kings', 'Chennai'), ('Delhi Capitals', 'Delhi'), ('Kings XI Punjab', 'Mohali'), ('Kolkata Knight Riders', 'Kolkata'), ('Mumbai Indians', 'Mumbai'), ('Rajasthan Royals', 'Jaipur'), ('Royal Challengers Bangalore', 'Bangalore'), ('Sunrisers Hyderabad', 'Hyderabad')])
type(ipl_teams.items())
dict_items
list(ipl_teams.items())
[('Chennai Super Kings', 'Chennai'),
 ('Delhi Capitals', 'Delhi'),
 ('Kings XI Punjab', 'Mohali'),
 ('Kolkata Knight Riders', 'Kolkata'),
 ('Mumbai Indians', 'Mumbai'),
 ('Rajasthan Royals', 'Jaipur'),
 ('Royal Challengers Bangalore', 'Bangalore'),
 ('Sunrisers Hyderabad', 'Hyderabad')]
type(list(ipl_teams.items()))
list
# Return keys in a dictionary
ipl_teams.keys()
dict_keys(['Chennai Super Kings', 'Delhi Capitals', 'Kings XI Punjab', 'Kolkata Knight Riders', 'Mumbai Indians', 'Rajasthan Royals', 'Royal Challengers Bangalore', 'Sunrisers Hyderabad'])
list(ipl_teams.keys())
['Chennai Super Kings',
 'Delhi Capitals',
 'Kings XI Punjab',
 'Kolkata Knight Riders',
 'Mumbai Indians',
 'Rajasthan Royals',
 'Royal Challengers Bangalore',
 'Sunrisers Hyderabad']
# Return values in a dictionary
list(ipl_teams.values())
['Chennai',
 'Delhi',
 'Mohali',
 'Kolkata',
 'Mumbai',
 'Jaipur',
 'Bangalore',
 'Hyderabad']
# Remove a key from a dictionary, if it is present and return its value
ipl_teams.pop('Chennai Super Kings')
'Chennai'
ipl_teams
{'Delhi Capitals': 'Delhi',
 'Kings XI Punjab': 'Mohali',
 'Kolkata Knight Riders': 'Kolkata',
 'Mumbai Indians': 'Mumbai',
 'Rajasthan Royals': 'Jaipur',
 'Royal Challengers Bangalore': 'Bangalore',
 'Sunrisers Hyderabad': 'Hyderabad'}
# If the key is not present then it will raise KeyError
# provide a default value to avoid KeyError
ipl_teams.pop('chennai Super Kings', -1)
-1
# Remove the last key-value pair and return it as a tuple
ipl_teams.popitem()
('Sunrisers Hyderabad', 'Hyderabad')
ipl_teams
{'Delhi Capitals': 'Delhi',
 'Kings XI Punjab': 'Mohali',
 'Kolkata Knight Riders': 'Kolkata',
 'Mumbai Indians': 'Mumbai',
 'Rajasthan Royals': 'Jaipur',
 'Royal Challengers Bangalore': 'Bangalore'}
# Merging two dictionaries
# d.update(d2) is used to merge two dictionaries
# If the key is not present in the first dictionary, it will be added
# If the key is present in the first dictionary, it will be updated with the value in the second dictionary
ipl_teams.update(ipl_teams_nested)
ipl_teams
{'Delhi Capitals': {'city': 'Delhi',
  'owner': 'GMR Group and JSW Group',
  'coach': 'Ricky Ponting',
  'captain': 'Rishabh Pant',
  'home_ground': 'Arun Jaitley Stadium'},
 'Kings XI Punjab': 'Mohali',
 'Kolkata Knight Riders': 'Kolkata',
 'Mumbai Indians': 'Mumbai',
 'Rajasthan Royals': 'Jaipur',
 'Royal Challengers Bangalore': 'Bangalore',
 'Chennai Super Kings': {'city': 'Chennai',
  'owner': 'Chennai Super Kings Cricket Ltd',
  'coach': 'Stephen Fleming',
  'captain': 'MS Dhoni',
  'home_ground': 'M. A. Chidambaram Stadium'}}