ProCodebaseProCodebase
  • ModusA Growth OS for your business, on WhatsAppKiosqSell more. Chase less.AI InterviewerAutomated screening & AI-led interviewsXperto AIAI prep companion for candidatesAI Tools HubResume builder, learning paths & more
  • Pre-Vetted DevelopersScreened, scored and ready to interviewAI-Native DevelopersSenior engineers on an hourly basis
  • Services
  • Features
  • AI Coaching
  • Jobs
  • FAQs
Sign inBook a demo
  • Services
  • Features
  • AI Coaching
  • Jobs
  • FAQs
Sign inBook a demo
ProCodebaseProCodebase

ProCodebase Technologies builds AI products for hiring and growth, and ships software for clients as a technical consultancy. We source, screen and deliver pre-vetted developers — so you only interview high-signal candidates.

Products

  • Modus
  • Kiosq
  • AI Interviewer
  • Xperto AI
  • AI Tools Hub

Hire & build

  • Pre-Vetted Developers
  • AI-Native Developers
  • Technical Consultancy
  • MVP Development
  • Features

Resources

  • Articles
  • Topics
  • Certifications
  • Collections
  • Jobs

Company

  • About Us
  • Contact Us
  • Book a Demo
  • FAQs

© 2026 ProCodebase Technologies. All rights reserved.

  • Privacy Policy
  • Terms & Conditions
  • Refund & Cancellation

Level Up Your Skills with Xperto-AI

A multi-AI agent platform that helps you level up your development skills and ace your interview preparation to secure your dream job.

Launch Xperto-AI

Understanding Dictionaries and Key-Value Pairs in Python

author
Generated by
Abhishek Goyan

21/09/2024

Python

Sign in to read full article

Dictionaries are one of the most versatile data structures in Python. They allow you to store data in a way that is easy to retrieve, modify, and manage. At the core of a dictionary are key-value pairs, which act as an efficient way to link related data.

What is a Dictionary?

A dictionary in Python is an unordered collection of items. Each item is stored as a pair of a key and its corresponding value. Each key must be unique within a dictionary, while multiple keys can point to the same value, allowing for a flexible structure that represents real-world data better than traditional lists or arrays.

Creating a Dictionary

To create a dictionary, you can use curly braces {} or the dict() constructor. Here’s how you can do both:

# Using curly braces my_dict = { "name": "Alice", "age": 30, "city": "London" } # Using the dict() constructor my_dict = dict(name="Alice", age=30, city="London")

In both cases, we end up with a dictionary named my_dict containing three key-value pairs.

Accessing Values

You can access the value associated with a key by using square brackets []. If the key exists, it will return the value; if not, you'll get a KeyError. For example:

print(my_dict["name"]) # Output: Alice print(my_dict["age"]) # Output: 30

Modifying Values

Dictionaries allow for easy updates. You can change an existing value by assigning a new value to its key:

my_dict["age"] = 31 print(my_dict["age"]) # Output: 31

You can also add new key-value pairs:

my_dict["occupation"] = "Engineer" print(my_dict) # Output: {'name': 'Alice', 'age': 31, 'city': 'London', 'occupation': 'Engineer'}

Removing Key-Value Pairs

If you want to remove a specific key-value pair from a dictionary, you can use the del keyword or the pop() method. Here’s how both are used:

del my_dict["city"] # Removes the key 'city' print(my_dict) # Output: {'name': 'Alice', 'age': 31, 'occupation': 'Engineer'} # Alternatively using pop() occupation = my_dict.pop("occupation") print(occupation) # Output: Engineer print(my_dict) # Output: {'name': 'Alice', 'age': 31}

Iterating Through a Dictionary

You can easily iterate over keys, values, or both in a dictionary. Here’s how to do that:

# Iterating through keys for key in my_dict: print(key) # Iterating through values for value in my_dict.values(): print(value) # Iterating through key-value pairs for key, value in my_dict.items(): print(f"{key}: {value}")

Nested Dictionaries

Dictionaries can also be nested, which means you can have a dictionary as a value for a key. This allows for more complex data structures. Here’s an example:

people = { "Alice": { "age": 30, "city": "London" }, "Bob": { "age": 25, "city": "New York" } } print(people["Alice"]["city"]) # Output: London

Summary of Key Features

To wrap up the capabilities of dictionaries, here's a brief summary of their key features:

  • Dynamic Size: Unlike lists, the size of dictionaries can change based on additions and deletions of key-value pairs.
  • Fast Access: Dictionaries are implemented using hash tables, which allow for average-case O(1) time complexity for lookups, inserts, and deletions.
  • Flexible Data Types: Both keys and values can be of any immutable type. However, commonly used types for keys include strings, numbers, and tuples.
  • Unordered Collections: As of Python 3.7, dictionaries maintain the insertion order, making them behave more like ordered collections.

Dictionaries are an essential part of Python programming. Whether you're working on data processing, managing configurations, or handling JSON data, dictionaries will often become your go-to structure for organizing data efficiently.

Popular tags

PythonDictionariesKey-Value Pairs

Share now!

Like & bookmark

Related collections

  • Streamlit Mastery: From Basics to Advanced

    15/11/2024 · Python

  • PyTorch Mastery: From Basics to Advanced

    14/11/2024 · Python

  • Mastering Scikit-learn from Basics to Advanced

    15/11/2024 · Python

  • Mastering Pandas: From Foundations to Advanced Data Engineering

    25/09/2024 · Python

  • Mastering LangGraph: Stateful, Orchestration Framework

    17/11/2024 · Python

Related articles

  • Understanding Background Subtraction in Python with OpenCV

    06/12/2024 · Python

  • Enhancing Redis Security and Authentication in Python

    08/11/2024 · Python

  • Understanding Python Classes and Object-Oriented Programming

    21/09/2024 · Python

  • Redis Connections and Pipelines in Python

    08/11/2024 · Python

  • Understanding Variables and Data Types in Python

    21/09/2024 · Python

  • Named Entity Recognition with NLTK in Python

    22/11/2024 · Python

  • Contour Detection and Analysis in Python with OpenCV

    06/12/2024 · Python

Popular category

  • Python
  • Generative AI
  • Machine Learning
  • ReactJS
  • System Design