πŸ“–

Exploring Python Dictionaries Basics

May 7, 2025

Understanding Dictionaries in Python

Introduction to Dictionaries

  • Dictionaries are one of four basic collection types in Python, alongside lists, sets, and tuples.
  • Consist of key-value pairs.
  • Ordered and changeable.
  • No duplicate keys allowed.

Creating a Dictionary

  • Syntax: dictionary_name = {}.
  • Example - Dictionary of countries and capitals: capitals = { "USA": "Washington DC", "India": "New Delhi", "China": "Beijing", "Russia": "Moscow" }

Useful Functions

  • dir(): Lists all attributes and methods of a dictionary.
    • Usage: dir(capitals).
  • help(): Provides in-depth description of attributes and methods.

Accessing Values

  • Use get() method to retrieve values:
    • Syntax: capitals.get("USA") returns "Washington DC".
    • If key is not found, returns None.
    • Example in an if statement: if capitals.get("Japan"): print("Capital exists") else: print("Capital doesn't exist")

Modifying Dictionaries

  • Update dictionary: Use update() to add or change key-value pairs.
    • Add: capitals.update({"Germany": "Berlin"}).
    • Change existing: capitals.update({"USA": "Detroit"}).
  • Remove entries:
    • pop(): Removes key-value pair by key.
      • Example: capitals.pop("China").
    • popitem(): Removes the last inserted key-value pair.
  • Clear dictionary: clear() method removes all items.

Accessing Keys and Values

  • Keys:
    • Use keys() method: keys = capitals.keys().
    • Iterable in a for loop: for key in capitals.keys(): print(key)
  • Values:
    • Use values() method: values = capitals.values().
    • Iterable in a for loop: for value in capitals.values(): print(value)
  • Items:
    • Use items() method: items = capitals.items().
    • Returns a view resembling a 2D list of tuples.
    • Iterable in a for loop: for key, value in capitals.items(): print(f"{key}: {value}")

Summary

  • Dictionaries: Collection of key-value pairs.
  • Ordered, changeable, no duplicates.
  • Methods include get, update, pop, popitem, clear, keys, values, items.
  • Useful for various programming tasks, including future game programming projects.