StudyLover
  • Home
  • Study Zone
  • Profiles
  • Typing Tutor
  • Contact us
  • Sign in
StudyLover Dictionaries
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
Sets : Control structures
Unit 3: Getting Started with Python: A Guide to Syntax, Data Structures, and OOP

A dictionary in Python is a mutable, ordered (as of Python 3.7) collection that stores data in key-value pairs. It's a highly versatile data structure used to create mappings, where each unique key is associated with a specific value. Dictionaries are created by placing comma-separated key: value pairs inside curly braces {}.

Key Characteristics of Dictionaries

  • Key-Value Pairs: The fundamental structure. You use a key to access its corresponding value.

  • Mutable: You can change, add, or remove key-value pairs after the dictionary is created.

  • Ordered: Dictionaries remember the insertion order of their items.

  • Unique Keys: Keys must be unique within a dictionary. If you add a key that already exists, its value will be updated.

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

Python

# A dictionary representing a person

person = {

    "name": "Neha",

    "age": 29,

    "city": "Mumbai",

    "skills": ["Python", "Data Analysis"]

}

 

print(f"A sample dictionary: {person}")


Operations with Operators

Indexing ([]) for Accessing and Modifying

You use square brackets to access the value associated with a key. If the key doesn't exist, it will raise a KeyError. You can also use this syntax to add a new key-value pair or update an existing one.

Python

# Accessing a value

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

 

# Updating a value

person['age'] = 30

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

 

# Adding a new key-value pair

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

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

Membership Testing (in, not in)

This operator checks for the presence of a key in the dictionary.

Python

# Check if a key exists

print(f"Is 'city' a key in the dictionary? {'city' in person}")       # Output: True

print(f"Is 'country' a key in the dictionary? {'country' in person}") # Output: False


Built-in Functions for Dictionaries

len()

Returns the number of key-value pairs in the dictionary.

Python

print(f"Number of items in the dictionary: {len(person)}") # Output: 5

dict()

The constructor function, which can be used to create new dictionaries, often from other data structures.

Python

# Creating a dictionary from a list of key-value tuples

new_dict = dict([('a', 1), ('b', 2)])

print(f"Dictionary from list of tuples: {new_dict}")


Common Dictionary Methods

Accessing Items

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

Python

# Using .get() is safer for keys that might not exist

country = person.get('country', 'Not Specified')

print(f"Person's country: {country}")

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

Python

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

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

Python

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

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

Python

print(f"All items (key-value pairs): {person.items()}")

Modifying Items

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

Python

person.update({'city': 'Delhi', 'status': 'Active'})

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

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

Python

removed_email = person.pop('email')

print(f"Removed value: {removed_email}, Dictionary is now: {person}")

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

Python

last_item = person.popitem()

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

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

Python

person.clear()

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

Copying

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

Python

original_dict = {'a': 1, 'b': [2, 3]}

copied_dict = original_dict.copy()

copied_dict['a'] = 100

copied_dict['b'].append(4) # Note: Modifying the nested list affects the original

 

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

print(f"Copied dictionary: {copied_dict}")

Creating from Keys

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

Python

keys = ['name', 'email', 'role']

default_value = 'unknown'

new_user = dict.fromkeys(keys, default_value)

print(f"Dictionary from keys: {new_user}")


Looping Through Dictionaries

You can iterate over a dictionary in several ways, but using .items() is often the most convenient.

Python

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

 

print("\nLooping through keys:")

for key in student:

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

 

print("\nLooping through values:")

for value in student.values():

    print(f"  Value: {value}")

 

print("\nLooping through key-value pairs (preferred method):")

for key, value in student.items():

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

 

Sets Control structures
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