📚

Essential Guide to Python Dictionaries

Apr 22, 2025

Understanding Dictionaries in Python

Introduction to Dictionaries

  • A dictionary is one of the four basic collection types in Python.
  • Consists of key-value pairs.
  • Characteristics:
    • Ordered and changeable.
    • No duplicates allowed.

Creating a Dictionary

  • Example: Dictionary of countries and capitals.
  • Syntax: capitals = {} using curly braces.
  • Adding entries using key-value pairs:
    • Example: "USA": "Washington DC"
    • Entries are separated by commas.
  • Example entries:
    • USA: Washington DC
    • India: New Delhi
    • China: Beijing
    • Russia: Moscow

Dictionary Methods

Viewing Attributes and Methods

  • Use dir(dictionary_name) to see all attributes and methods.
  • Use help(dictionary_name) for detailed descriptions.

Accessing Values

  • Use get method: dictionary_name.get(key).
  • Example: capitals.get("USA") returns "Washington DC".
  • If the key doesn't exist, returns None.

Checking for Key Existence

  • Example: Check if a capital exists using an if statement.
    • if capitals.get("Japan"): print("Exists") else: print("Doesn't exist")

Updating a Dictionary

  • Use update method to add or update key-value pairs.
  • Example: capitals.update({"Germany": "Berlin"}).
  • Updating an existing key:
    • Example: capitals.update({"USA": "Detroit"}).

Removing Entries

  • Use pop to remove a specific key-value pair.
    • Example: capitals.pop("China").
  • Use popitem to remove the last inserted key-value pair.
  • Use clear to remove all entries from the dictionary.

Retrieving Keys and Values

Getting All Keys

  • Use keys method: dictionary_name.keys().
  • Returns an iterable object resembling a list.
  • Can be used in a loop to iterate over all keys.

Getting All Values

  • Use values method: dictionary_name.values().
  • Returns an iterable object resembling a list.
  • Can be used in a loop to iterate over all values.

Getting Key-Value Pairs

  • Use items method: dictionary_name.items().
  • Returns a dictionary object resembling a 2D list of tuples.
  • Can be used in a loop to iterate over key-value pairs.

Conclusion

  • Dictionaries are a flexible and powerful data structure in Python.
  • Essential methods include get, update, pop, popitem, clear, keys, values, items.
  • Useful for various applications, including future programming projects.