पायथन शब्दकोश और सेट्स का परिचय

Nov 17, 2024

Chapter 4: Python Dictionaries and Sets

Introduction

  • Dictionaries and Sets are important data structures in Python.
  • Built-in data types frequently used in Python coding.
  • Focus on special properties, methods, and practical applications.

Python Dictionaries

  • Dictionary Concept: Works like a real-life dictionary with word-meaning pairs.
  • Key-Value Pairs: Keys are like words, values are the meanings.
  • Creation: Use curly braces {} with key-value pairs separated by colons.
  • Example: { "name": "John", "age": 30 }.
  • Data Types: Keys and values can be strings, integers, floats, booleans, lists, and tuples.
  • Immutable Keys: Keys cannot be lists or dictionaries but can be strings, numbers, and tuples.
  • Properties:
    • Unordered: No fixed order.
    • Mutable: Can change values.
    • No duplicate keys.

Accessing Dictionary Values

  • Use key to access values: dictionary[key].
  • dict.get(key) method avoids errors if the key is missing.
  • Adding/Updating Values: Assign new values directly with dictionary[key] = value.
  • Nested Dictionaries: Dictionary within a dictionary.

Dictionary Methods

  • .keys(): Returns all keys as a list.
  • .values(): Returns all values.
  • .items(): Returns items as key-value tuples.
  • .update(): Adds new key-value pairs.
  • Checking Dictionary Type: type(dictionary) returns dict.

Python Sets

  • Concept: Similar to mathematical sets with unique elements.
  • Creation: Use curly braces {} or set() function.
  • Properties:
    • Unordered: No indexing.
    • Unique and Immutable Elements.
  • Adding/Removing Elements: .add() to add and .remove() to remove.
  • Empty Set: Use set() function.

Set Methods

  • .clear(): Empties the set.
  • .pop(): Removes a random element.
  • Union and Intersection:
    • union(): Combines unique elements from two sets.
    • intersection(): Finds common elements.

Practice Questions

  1. Dictionary Word Meanings: Store pairs like "table": ["piece of furniture", "list of facts"].
  2. Classroom Allocation: Use sets to find the number of unique classrooms needed.
  3. Enter Marks: Store subject marks in a dictionary using user input.
  4. Unique Set Values: Store 9 and 9.0 separately using strings or tuples for differentiation.

Conclusion

  • Dictionaries and sets are versatile data structures in Python.
  • Understanding their properties and methods is crucial for effective coding.
  • Practice and application in further chapters will enhance comprehension.