logologo
  • AI Tools

    DB Query GeneratorMock InterviewResume BuilderLearning Path GeneratorCheatsheet GeneratorAgentic Prompt GeneratorCompany ResearchCover Letter Generator
  • XpertoAI
  • MVP Ready
  • Resources

    CertificationsTopicsExpertsCollectionsArticlesQuestionsVideosJobs
logologo

Elevate Your Coding with our comprehensive articles and niche collections.

Useful Links

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

Resources

  • Xperto-AI
  • Certifications
  • Python
  • GenAI
  • Machine Learning

Interviews

  • DSA
  • System Design
  • Design Patterns
  • Frontend System Design
  • ReactJS

Procodebase © 2024. 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

  • LangChain Mastery: From Basics to Advanced

    26/10/2024 | Python

  • Mastering NLTK for Natural Language Processing

    22/11/2024 | Python

  • Mastering Scikit-learn from Basics to Advanced

    15/11/2024 | Python

  • Python with MongoDB: A Practical Guide

    08/11/2024 | Python

  • Mastering Computer Vision with OpenCV

    06/12/2024 | Python

Related Articles

  • Redis Persistence and Backup Strategies in Python

    08/11/2024 | Python

  • Contour Detection and Analysis in Python with OpenCV

    06/12/2024 | Python

  • Profiling and Optimizing Python Code

    13/01/2025 | Python

  • Understanding Python Syntax and Structure

    21/09/2024 | Python

  • Unraveling Image Segmentation in Python

    06/12/2024 | Python

  • Deep Learning Integration in Python for Computer Vision with OpenCV

    06/12/2024 | Python

  • Abstract Base Classes and Interface Design in Python

    13/01/2025 | Python

Popular Category

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