logologo
  • AI Interviewer
  • Features
  • AI Tools
  • FAQs
  • Jobs
logologo

Transform your hiring process with AI-powered interviews. Screen candidates faster and make better hiring decisions.

Useful Links

  • Contact Us
  • Privacy Policy
  • Terms & Conditions
  • Refund & Cancellation
  • About Us

Resources

  • Certifications
  • Topics
  • Collections
  • Articles
  • Services

AI Tools

  • AI Interviewer
  • Xperto AI
  • AI Pre-Screening

Procodebase © 2025. All rights reserved.

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

  • Mastering Pandas: From Foundations to Advanced Data Engineering

    25/09/2024 | Python

  • Mastering NLTK for Natural Language Processing

    22/11/2024 | Python

  • Python with Redis Cache

    08/11/2024 | Python

  • LlamaIndex: Data Framework for LLM Apps

    05/11/2024 | Python

  • Mastering LangGraph: Stateful, Orchestration Framework

    17/11/2024 | Python

Related Articles

  • Python Data Classes

    13/01/2025 | Python

  • Harnessing Python Asyncio and Event Loops for Concurrent Programming

    13/01/2025 | Python

  • Automating Emails and Notifications with Python

    08/12/2024 | Python

  • Text Classification Using NLTK in Python

    22/11/2024 | Python

  • Object Detection Basics with Python and OpenCV

    06/12/2024 | Python

  • Video Processing Fundamentals in Python

    06/12/2024 | Python

  • Working with APIs for Automation in Python

    08/12/2024 | Python

Popular Category

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