Sunday, January 12, 2025
HomeComputer SciencePython Dictionaries (with Examples)

Python Dictionaries (with Examples)

A dictionary in Python is a collection of key-value pairs. It is one of Python’s built-in data structures and is used to store data values like a map. Each key in a dictionary must be unique, immutable, and is associated with a value.

Characteristics of a Dictionary

  1. Unordered: The items are stored in an unordered manner (as of Python 3.7, dictionaries maintain insertion order).
  2. Mutable: You can add, modify, or remove items.
  3. Keys are Unique: No duplicate keys are allowed.
  4. Keys Must Be Immutable: Keys can be strings, numbers, or tuples (not lists or other dictionaries).

Creating a Dictionary

1. Using Curly Braces

python
my_dict = {
"name": "Alice",
"age": 25,
"city": "New York"
}
print(my_dict)
# Output: {'name': 'Alice', 'age': 25, 'city': 'New York'}

2. Using the dict() Constructor

python
my_dict = dict(name="Bob", age=30, city="Los Angeles")
print(my_dict)
# Output: {'name': 'Bob', 'age': 30, 'city': 'Los Angeles'}

Accessing Dictionary Items

  1. Using Keys
python
my_dict = {"name": "Alice", "age": 25}
print(my_dict["name"]) # Output: Alice
  1. Using the get() Method
python
print(my_dict.get("age")) # Output: 25
print(my_dict.get("gender", "Not Specified")) # Output: Not Specified

Adding and Modifying Items

python
my_dict = {"name": "Alice", "age": 25}
my_dict["city"] = "New York" # Add new key-value pair
my_dict["age"] = 26 # Modify existing key
print(my_dict)
# Output: {'name': 'Alice', 'age': 26, 'city': 'New York'}

Removing Items

  1. Using pop()
python
my_dict = {"name": "Alice", "age": 25, "city": "New York"}
my_dict.pop("age")
print(my_dict)
# Output: {'name': 'Alice', 'city': 'New York'}
  1. Using del
python
del my_dict["city"]
print(my_dict)
# Output: {'name': 'Alice'}
  1. Using clear()
python
my_dict.clear()
print(my_dict)
# Output: {}

Iterating Through a Dictionary

  1. Keys Only
python
my_dict = {"name": "Alice", "age": 25}
for key in my_dict:
print(key)
# Output: name
# age
  1. Values Only
python
for value in my_dict.values():
print(value)
# Output: Alice
# 25
  1. Keys and Values
python
for key, value in my_dict.items():
print(f"{key}: {value}")
# Output: name: Alice
# age: 25

Checking for Keys

python
my_dict = {"name": "Alice", "age": 25}
print("name" in my_dict) # Output: True
print("gender" in my_dict) # Output: False

Dictionary Methods

Method Description
get(key, default) Returns the value for the specified key.
keys() Returns a view object of all the keys.
values() Returns a view object of all the values.
items() Returns a view object of all the key-value pairs.
pop(key) Removes the specified key and returns its value.
popitem() Removes and returns the last inserted key-value pair (from Python 3.7 onward).
clear() Removes all items from the dictionary.
update(other_dict) Updates the dictionary with items from another dictionary or iterable.
See also  What Is Computer Science?

Examples of Real-World Usage

  1. Storing User Data
python
user = {"username": "johndoe", "email": "[email protected]", "is_active": True}
  1. Counting Occurrences
python
from collections import Counter

text = "apple banana apple orange"
word_count = Counter(text.split())
print(word_count)
# Output: {'apple': 2, 'banana': 1, 'orange': 1}

  1. Representing JSON Data
python
import json

data = '{"name": "Alice", "age": 25, "city": "New York"}'
parsed = json.loads(data)
print(parsed)
# Output: {'name': 'Alice', 'age': 25, 'city': 'New York'}

Dictionaries are a versatile and essential tool in Python, enabling efficient storage and manipulation of data through key-value pairs.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x