StudyLover
  • Home
  • Study Zone
  • Profiles
  • Typing Tutor
  • Contact us
  • Sign in
StudyLover dict (Dictionary)
Download
  1. Python
  2. Pyhton MCA (Machine Learning using Python)
  3. Unit 3: Getting Started with Python: A Guide to Syntax, Data Structures, and OOP
Range : Set
Unit 3: Getting Started with Python: A Guide to Syntax, Data Structures, and OOP

A dictionary in Python is a powerful and flexible data type used to store a collection of key-value pairs. It's a mapping type, meaning it maps unique keys to corresponding values. Dictionaries are created by placing a comma-separated list of key: value pairs inside curly braces {}.


Key Characteristics of Dictionaries

  • Key-Value Pairs: The fundamental structure of a dictionary. Each key is used to access its associated value.

  • Mutable: Dictionaries are changeable. You can add, remove, and modify key-value pairs after the dictionary has been created.

  • Ordered (since Python 3.7): Dictionaries remember the order in which items were inserted. In earlier versions of Python, they were unordered.

  • Unique Keys: The keys in a dictionary must be unique. If you try to add a key that already exists, its value will be updated.

  • Keys Must be Immutable: The keys of a dictionary must be of an immutable data type (like strings, numbers, or tuples). The values, however, can be of any data type.


Operations on Dictionaries

  • Accessing Items: You access the value associated with a key using square bracket notation: my_dict['key'].

  • Adding / Updating Items: You can add a new key-value pair or update an existing one using the same square bracket notation: my_dict['new_key'] = 'new_value'.

  • Membership Testing (in, not in): This checks for the presence of a key in the dictionary.


Built-in Functions for Dictionaries

  • len(): Returns the number of key-value pairs in the dictionary.

  • dict(): The constructor function, used to create new dictionaries.

  • str(): Returns a string representation of the dictionary.


Common Dictionary Methods

Methods are functions called on a dictionary object itself (e.g., my_dict.get()).

Accessing Items

  • .get(key, default): Returns the value for a specified key. The advantage over square brackets is that it won't raise an error if the key doesn't exist; instead, it returns None or a specified default value.

  • .keys(): Returns a view object that displays a list of all the keys in the dictionary.

  • .values(): Returns a view object that displays a list of all the values in the dictionary.

  • .items(): Returns a view object that displays a list of key-value tuple pairs. This is very useful for looping.

Modifying Items

  • .update(other_dict): Updates the dictionary with the key-value pairs from another dictionary or an iterable of key-value pairs.

  • .pop(key): Removes the specified key and returns its corresponding value.

  • .popitem(): Removes and returns the last inserted key-value pair (in Python 3.7+).

  • .clear(): Removes all items from the dictionary.

Other Methods

  • .copy(): Returns a shallow copy of the dictionary.

  • .fromkeys(keys, value): A class method that creates a new dictionary from an iterable of keys, with all keys having the same specified value.

 

# --- 1. Dictionary Creation ---

# Dictionaries store data in key-value pairs.

empty_dict = {}

person = {

    "name": "Neha",

    "age": 28,

    "city": "Mumbai"

}

print(f"A dictionary representing a person: {person}")

 

# --- 2. Accessing Items ---

print("\n--- Accessing Items ---")

# Accessing with square brackets (raises an error if key is not found)

print(f"Person's name: {person['name']}")

 

# Accessing with .get() (returns None or a default value if key is not found)

print(f"Person's email: {person.get('email')}")

print(f"Person's country (default 'India'): {person.get('country', 'India')}")

 

# --- 3. Modifying a Dictionary ---

print("\n--- Modifying a Dictionary ---")

print(f"Original dictionary: {person}")

# Add a new key-value pair

person["email"] = "Neha@example.com"

print(f"After adding email: {person}")

# Update an existing value

person["age"] = 29

print(f"After updating age: {person}")

 

# --- 4. Dictionary Methods: Accessing Keys, Values, and Items ---

print("\n--- Accessing Keys, Values, and Items ---")

# .keys() returns a view of all keys

print(f"Keys: {person.keys()}")

# .values() returns a view of all values

print(f"Values: {person.values()}")

# .items() returns a view of all key-value pairs (as tuples)

print(f"Items: {person.items()}")

 

# --- 5. Dictionary Methods: Modifying and Removing ---

print("\n--- Modifying and Removing ---")

# .update() merges another dictionary

person.update({"country": "India", "is_employed": True})

print(f"After .update(): {person}")

 

# .pop() removes a key and returns its value

removed_city = person.pop("city")

print(f"Popped value: '{removed_city}', Dictionary is now: {person}")

 

# .popitem() removes and returns the last inserted item

last_item = person.popitem()

print(f"Popped item: {last_item}, Dictionary is now: {person}")

 

# .clear() removes all items

person.clear()

print(f"After .clear(): {person}")

 

# --- 6. Looping Through a Dictionary ---

print("\n--- Looping Through a Dictionary ---")

student = {"name": "Arjun", "major": "Computer Science", "gpa": 3.8}

# Loop through keys

print("Looping through keys:")

for key in student:

    print(f"  {key}: {student[key]}")

 

# Loop through key-value pairs using .items() (preferred way)

print("\nLooping through items:")

for key, value in student.items():

    print(f"  {key} -> {value}")

 

# --- 7. Built-in Functions with Dictionaries ---

print("\n--- Built-in Functions ---")

print(f"Length of student dictionary: {len(student)}")

Range Set
Our Products & Services
  • Home
Connect with us
  • Contact us
  • +91 82955 87844
  • Rk6yadav@gmail.com

StudyLover - About us

The Best knowledge for Best people.

Copyright © StudyLover
Powered by Odoo - Create a free website