Data Science Hub
  • Data Science Hub
  • STATISTICS
    • Introduction
    • Fundamentals
      • Data Types
      • Central Tendency, Asymmetry, and Variability
      • Sampling
      • Confidence Interval
      • Hypothesis Testing
    • Distributions
      • Exponential Distribution
    • A/B Testing
      • Sample Size Calculation
      • Multiple Testing
  • Database
    • Database Fundamentals
    • Database Management Systems
    • Data Warehouse vs Data Lake
  • SQL
    • SQL Basics
      • Creating and Modifying Tables/Views
      • Data Types
      • Joins
    • SQL Rules
    • SQL Aggregate Functions
    • SQL Window Functions
    • SQL Data Manipulation
      • String Operations
      • Date/Time Operations
    • SQL Descriptive Stats
    • SQL Tips
    • SQL Performance Tuning
    • SQL Customization
    • SQL Practice
      • Designing Databases
        • Spotify Database Design
      • Most Commonly Asked
      • Mixed Queries
      • Popular Websites For SQL Practice
        • SQLZoo
          • World - BBC Tables
            • SUM and COUNT Tutorial
            • SELECT within SELECT Tutorial
            • SELECT from WORLD Tutorial
            • Select Quiz
            • BBC QUIZ
            • Nested SELECT Quiz
            • SUM and COUNT Quiz
          • Nobel Table
            • SELECT from Nobel Tutorial
            • Nobel Quiz
          • Soccer / Football Tables
            • JOIN Tutorial
            • JOIN Quiz
          • Movie / Actor / Casting Tables
            • More JOIN Operations Tutorial
            • JOIN Quiz 2
          • Teacher - Dept Tables
            • Using Null Quiz
          • Edinburgh Buses Table
            • Self join Quiz
        • HackerRank
          • SQL (Basic)
            • Select All
            • Select By ID
            • Japanese Cities' Attributes
            • Revising the Select Query I
            • Revising the Select Query II
            • Revising Aggregations - The Count Function
            • Revising Aggregations - The Sum Function
            • Revising Aggregations - Averages
            • Average Population
            • Japan Population
            • Population Density Difference
            • Population Census
            • African Cities
            • Average Population of Each Continent
            • Weather Observation Station 1
            • Weather Observation Station 2
            • Weather Observation Station 3
            • Weather Observation Station 4
            • Weather Observation Station 6
            • Weather Observation Station 7
            • Weather Observation Station 8
            • Weather Observation Station 9
            • Weather Observation Station 10
            • Weather Observation Station 11
            • Weather Observation Station 12
            • Weather Observation Station 13
            • Weather Observation Station 14
            • Weather Observation Station 15
            • Weather Observation Station 16
            • Weather Observation Station 17
            • Weather Observation Station 18
            • Weather Observation Station 19
            • Higher Than 75 Marks
            • Employee Names
            • Employee Salaries
            • The Blunder
            • Top Earners
            • Type of Triangle
            • The PADS
          • SQL (Intermediate)
            • Weather Observation Station 5
            • Weather Observation Station 20
            • New Companies
            • The Report
            • Top Competitors
            • Ollivander's Inventory
            • Challenges
            • Contest Leaderboard
            • SQL Project Planning
            • Placements
            • Symmetric Pairs
            • Binary Tree Nodes
            • Interviews
            • Occupations
          • SQL (Advanced)
            • Draw The Triangle 1
            • Draw The Triangle 2
            • Print Prime Numbers
            • 15 Days of Learning SQL
          • TABLES
            • City - Country
            • Station
            • Hackers - Submissions
            • Students
            • Employee - Employees
            • Occupations
            • Triangles
        • StrataScratch
          • Netflix
            • Oscar Nominees Table
            • Nominee Filmography Table
            • Nominee Information Table
          • Audible
            • Easy - Audible
          • Spotify
            • Worldwide Daily Song Ranking Table
            • Billboard Top 100 Year End Table
            • Daily Rankings 2017 US
          • Google
            • Easy - Google
            • Medium - Google
            • Hard - Google
        • LeetCode
          • Easy
  • Python
    • Basics
      • Variables and DataTypes
        • Lists
        • Dictionaries
      • Control Flow
      • Functions
    • Object Oriented Programming
      • Restaurant Modeler
    • Pythonic Resources
    • Projects
  • Machine Learning
    • Fundamentals
      • Supervised Learning
        • Classification Algorithms
          • k-Nearest Neighbors
            • kNN Parameters & Attributes
          • Logistic Regression
        • Classification Report
      • UnSupervised Learning
        • Clustering
          • Evaluation
      • Preprocessing
        • Scalers: Standard vs MinMax
        • Feature Selection vs Dimensionality Reduction
        • Encoding
    • Frameworks
    • Machine Learning in Advertising
    • Natural Language Processing
      • Stopwords
      • Name Entity Recognition (NER)
      • Sentiment Analysis
        • Agoda Reviews - Part I - Scraping Reviews, Detecting Languages, and Preprocessing
        • Agoda Reviews - Part II - Sentiment Analysis and WordClouds
    • Recommendation Systems
      • Spotify Recommender System - Artists
  • Geospatial Analysis
    • Geospatial Analysis Basics
    • GSA at Work
      • Web Scraping and Mapping
  • GIT
    • GIT Essentials
    • Connecting to GitHub
  • FAQ
    • Statistics
  • Cloud Computing
    • Introduction to Cloud Computing
    • Google Cloud Platform
  • Docker
    • What is Docker?
Powered by GitBook
On this page
  • 1. Accessing Dictionaries Elements
  • 2. Updating Dictionaries
  • 2.1. Adding new key-value pairs
  • 2.2. Deleting new key-value pairs
  • 3. Dictionary Methods
  • Conclusion

Was this helpful?

  1. Python
  2. Basics
  3. Variables and DataTypes

Dictionaries

Dictionaries in Python are created using curly braces {} and consist of key-value pairs separated by colons :. They are unordered collections of key-value pairs that allow for efficient lookup, insertion, and deletion of items based on their keys. Each key in a dictionary must be unique and immutable, such as strings, numbers, or tuples. Keys are used to access corresponding values, which can be any data type, including lists, tuples, or even other dictionaries.

Dataset:

basketball_champions_top10= {
    'Los Angeles Lakers': 17,
    'Boston Celtics': 17,
    'Golden State Warriors': 7,
    'Chicago Bulls': 6,
    'San Antonio Spurs': 5,
    'Philadelphia 76ers': 3,
    'Detroit Pistons': 3,
    'Miami Heat': 3,
    'New York Knicks': 2,
    'Houston Rockets': 2,
    'Milwaukee Bucks': 2,
}

1. Accessing Dictionaries Elements

# Print out the keys in basketball_champions
print(f"Keys: \n{basketball_champions_top10.keys()}\n")

# Print out the values in basketball_champions
print(f"Values: \n{basketball_champions_top10.values()}\n")

# Print out all key-value pairs with items()
print(f"Items: \n{basketball_champions_top10.items()}\n")

# Print out championship counts for 'Boston Celtics'
print(f"Boston Celtics championships: {basketball_champions_top10['Boston Celtics']}")


#OUTPUT
"""
Keys: 
dict_keys(['Los Angeles Lakers', 'Boston Celtics', 'Golden State Warriors', 'Chicago Bulls', 'San Antonio Spurs', 'Philadelphia 76ers', 'Detroit Pistons', 'Miami Heat', 'New York Knicks', 'Houston Rockets'])

Values: 
dict_values([17, 17, 7, 6, 5, 3, 3, 3, 2, 2])

Items: 
dict_items([('Los Angeles Lakers', 17), ('Boston Celtics', 17), ('Golden State Warriors', 7), ('Chicago Bulls', 6), ('San Antonio Spurs', 5), ('Philadelphia 76ers', 3), ('Detroit Pistons', 3), ('Miami Heat', 3), ('New York Knicks', 2), ('Houston Rockets', 2)])

Boston Celtics championships: 17
"""

Unlike Python Lists , which are indexed by integers, Dictionaries are indexed by unique keys.

2. Updating Dictionaries

2.1. Adding new key-value pairs

# unlike lists, dictionaries dict['new_key']=new_value syntax
# add 'Milwaukee Bucks' who has 2 championships
basketball_champions_top10 += {'Milwaukee Bucks': 2} # Error

#OUTPUT
"""
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[14], line 4
      1 # Adding new key-value pairs
      2 # unlike lists, dictionaries dict['new_key']=new_value syntax
      3 # add 'Milwaukee Bucks' who has 2 championships
----> 4 basketball_champions_top10 += {'Milwaukee Bucks': 2} # Error

TypeError: unsupported operand type(s) for +=: 'dict' and 'dict'
"""


# correct way
basketball_champions_top10['Milwaukee Bucks']= 2
print(basketball_champions_top10)
print("---------------------")

# or using the method update()
basketball_champions_top10.update({'Cleveland Cavaliers': 1})
print(basketball_champions_top10)


#OUTPUT
"""
{'Los Angeles Lakers': 17, 'Boston Celtics': 17, 'Golden State Warriors': 7, 
'Chicago Bulls': 6, 'San Antonio Spurs': 5, 'Philadelphia 76ers': 3, 
'Detroit Pistons': 3, 'Miami Heat': 3, 'New York Knicks': 2, 'Houston Rockets': 2, 
'Milwaukee Bucks': 2}
---------------------
{'Los Angeles Lakers': 17, 'Boston Celtics': 17, 'Golden State Warriors': 7, 
'Chicago Bulls': 6, 'San Antonio Spurs': 5, 'Philadelphia 76ers': 3, 
'Detroit Pistons': 3, 'Miami Heat': 3, 'New York Knicks': 2, 'Houston Rockets': 2, 
'Milwaukee Bucks': 2, 'Cleveland Cavaliers': 1}
"""

2.2. Deleting new key-value pairs

# delete 'Cleveland Cavaliers' and 'Milwaukee Bucks' and their values
# a. using del
del basketball_champions_top10['Cleveland Cavaliers']

# b. using .pop()
basketball_champions_top10.pop('Milwaukee Bucks')
print(basketball_champions_top10)

#OUTPUT
"""
{'Los Angeles Lakers': 17, 'Boston Celtics': 17, 'Golden State Warriors': 7, 
'Chicago Bulls': 6, 'San Antonio Spurs': 5, 'Philadelphia 76ers': 3, 
'Detroit Pistons': 3, 'Miami Heat': 3, 'New York Knicks': 2, 'Houston Rockets': 2}
"""

3. Dictionary Methods

Method
Description

Removes all the elements from the dictionary

Returns a copy of the dictionary

Returns a dictionary with the specified keys and value

Returns the value of the specified key

Returns a list containing a tuple for each key value pair

Returns a list containing the dictionary's keys

Removes the element with the specified key

Removes the last inserted key-value pair

Returns the value of the specified key. If the key does not exist: insert the key, with the specified value

Updates the dictionary with the specified key-value pairs

Returns a list of all the values in the dictionary

Click on the methods practice them on W3schools

# get the value for a specific key
print(basketball_champions_top10.get('Boston Celtics'))
# remove the last item
print(basketball_champions_top10.popitem())

#OUTPUT
"""
17
('Houston Rockets', 2)
"""

Conclusion

Dictionaries in Python are versatile data structures that store key-value pairs. Keys, which must be immutable and unique within a dictionary, are used to access associated values, which can be of any data type. Dictionaries provide a flexible way to organize and manipulate data, supporting operations like insertion, deletion, and modification of key-value pairs. They are commonly used to represent mappings/configurations and are fundamental in Python programming for their ability to provide efficient data organization and retrieval for various applications.

Last updated 1 year ago

Was this helpful?

clear()
copy()
fromkeys()
get()
items()
keys()
pop()
popitem()
setdefault()
update()
values()
Page cover image