Телеграм

Artificial Intelligence

@machinelearning_deeplearning Программирование и разработка
РКН: проверяем Иноагент: проверяем
🔰 Machine Learning & Artificial Intelligence Free Resources

🔰 Learn Data Science, Deep Learning, Python with Tensorflow, Keras & many more

For Promotions: @love_data

Статистика обновлена 12.11.2026 в 18:32 · 1 просмотр страницы · Хотите больше просмотров?

Подписчики56 702
Охват поста2 964 5% от подписчиков
ERR за месяц5,23%
ERR за 24 часа3,11%

Динамика за 30 дней

Рекламные публикации

Рекламных публикаций не найденоЗа последнее время мы не нашли на площадке ни одного рекламного поста.

Последние публикации

Все посты канала →
Artificial Intelligence tg56 тыс. подписчиков
Открыть пост ↗
Just like list comprehensions, Python supports dictionary comprehensions.

squares = {x: x * x for x in range(1, 6)}
# {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

even_squares = {
    x: x * x
    for x in range(1, 6)
    if x % 2 == 0
}
# {2: 4, 4: 16}


🔹 13. Dictionary Keys Must Be Hashable

Dictionary keys must be hashable.

Valid examples:
data = {
    "name": "Alex",
    10: "ten",
    (1, 2): "tuple"
}


❌ A list cannot be used as a key.

data = {
    [1, 2]: "numbers"
} # TypeError

Because lists are mutable and therefore unhashable.

🔹 14. Can Dictionary Values Be Mutable?

Yes! Values can be almost any Python object.
data = {
    "numbers": [1, 2, 3],
    "info": {"age": 21}
}

So:
Keys → must be hashable
Values → can be mutable or immutable

🤖 Dictionaries in AI & Data Science

Dictionaries are everywhere in AI applications.

API responses
response = {
    "status": "success",
    "score": 0.94,
    "model": "classifier"
}
Configuration
config = {
    "learning_rate": 0.001,
    "epochs": 10,
    "batch_size": 32
}
Feature mapping
features = {
    "age": 25,
    "income": 60000,
    "experience": 3
}

JSON data - JSON objects map naturally to Python dictionaries.

This makes dictionaries particularly important when working with REST APIs, machine learning pipelines, LLM APIs, and configuration files.

⚠️ Common Beginner Mistakes

❌ Mistake 1: Using an index
student[0]

- Dictionaries are accessed using keys, not numerical indexes.

❌ Mistake 2: Assuming duplicate keys are preserved
data = {
    "name": "Alex",
    "name": "Sam"
} # {'name': 'Sam'}

The final value wins.

❌ Mistake 3: Confusing keys and values
"name" in student

checks whether "name" is a key.

💡 Key Takeaways

✅ Dictionaries store key-value pairs
✅ Keys must be unique
✅ Keys must be hashable
✅ Values can be of different data types
✅ Use [] for direct access
✅ Use .get() when a missing key should be handled safely
✅ .keys(), .values(), and .items() are important methods
✅ Dictionaries support nested structures and comprehensions
✅ They are heavily used in APIs, JSON, AI applications, and data processing

🔥 Mastering dictionaries is essential because you'll use them constantly when working with Python, APIs, data science, machine learning, and AI systems.

Double Tap ❤️ For More
👁 478 ❤ 2 ↻ 1 сегодня в 06:02
Artificial Intelligence tg56 тыс. подписчиков
Открыть пост ↗
In the previous topic, we learned about Sets — how they store unique values, perform set operations, and are useful for fast membership checking.

Now let's move to another extremely important Python data structure.

📖 Phase 1: Programming Fundamentals

📌 Topic 18: Dictionaries in Python 🗂️

A dictionary is a Python data structure used to store data in key-value pairs.

In Python:

student = {
"name": "Alex",
"age": 21,
"course": "Python"
}


Here:
"name" → key
"Alex" → value
"age" → key
21 → value

🔹 1. Why Do We Need Dictionaries?

Suppose you have this list:

student = ["Alex", 21, "Python"]


You need to remember that:
Index 0 = name
Index 1 = age
Index 2 = course

That's not very readable.

With a dictionary:

student = {
"name": "Alex",
"age": 21,
"course": "Python"
}

print(student["name"])


Output:

Alex


🔹 2. Creating a Dictionary

Use curly braces {} with key-value pairs:

person = {
"name": "John",
"age": 25,
"city": "Delhi"
}


You can also create an empty dictionary:

data = {}

# Or

data = dict()


⚠️ Remember: {} creates an empty dictionary, not an empty set. For an empty set: set()

🔹 3. Dictionary Keys and Values

A dictionary contains: Key → Value

employee = {
"name": "Sam",
"salary": 50000,
"department": "IT"
}


Keys: name, salary, department

Values: Sam, 50000, IT

You can get them using:

employee.keys()
employee.values()
employee.items()


🔹 4. Accessing Dictionary Values

Using a key:

student = {
"name": "Alex",
"age": 21
}

print(student["name"]) # Alex


You can also use .get():

print(student.get("name")) # Alex


What is the difference?

If the key doesn't exist:
student["city"] ❌ Raises KeyError.

But:
student.get("city") ✅ Returns: None

You can also provide a default value:

student.get("city", "Unknown") # Output: Unknown


🔹 5. Adding New Items

Simply assign a value to a new key:

student = {
"name": "Alex",
"age": 21
}

student["city"] = "Delhi"
print(student)
# {'name': 'Alex', 'age': 21, 'city': 'Delhi'}


🔹 6. Updating Values

If the key already exists, assignment changes its value:

student["age"] = 22


You can also use .update():

student.update({
"age": 23,
"city": "Mumbai"
})


🔹 7. Removing Items

pop() - Removes a specific key and returns its value.

student.pop("age")


del removes a specific key:

del student["city"]


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

student.popitem()


clear() - Removes everything:

student.clear()


🔹 8. Checking Whether a Key Exists

Use the in operator:

student = {
"name": "Alex",
"age": 21
}

print("name" in student) # Output: True


Important: "name" in student checks keys, not values.

🔹 9. Looping Through a Dictionary

Loop through keys:

for key in student:
print(key)


Loop through values:

for value in student.values():
print(value)


Loop through both:

for key, value in student.items():
print(key, value)


This is one of the most commonly used patterns when working with dictionaries.

🔹 10. Dictionary Length

Use len():

student = {
"name": "Alex",
"age": 21,
"course": "Python"
}

print(len(student))
# Output: 3


len() counts the number of key-value pairs.

🔹 11. Nested Dictionaries

A dictionary can contain another dictionary.

students = {
"student1": {
"name": "Alex",
"age": 21
},
"student2": {
"name": "Sam",
"age": 22
}
}

print(students["student1"]["name"]) # Output: Alex


Nested dictionaries are extremely common when working with structured data and APIs.

🔹 12. Dictionary Comprehension
👁 404 ❤ 1 ↻ 2 сегодня в 06:01
Artificial Intelligence tg56 тыс. подписчиков
Открыть пост ↗
When Should You Use a Tuple?

Use a tuple when the collection represents data that should remain fixed.

For example:

image_size = (1920, 1080)


The width and height form a fixed pair of values.

Tuples are also commonly used for coordinates:

point = (10, 25)


11. Tuples in AI and Data Science

Tuples appear frequently in Python-based AI applications.

For example, a dataset might contain:

sample = ("image_001.jpg", 1)


Here, the tuple can represent:

• File name

• Corresponding label

Tuples are also frequently encountered when working with functions that return multiple values, database results, coordinates, and fixed configurations.

⚠️ Important: Immutable Doesn't Always Mean Completely Unchangeable

A tuple itself is immutable, but it can contain mutable objects.

For example:

data = ([1, 2], [3, 4])
data[0].append(5)
print(data)


Output:

([1, 2, 5], [3, 4])


The tuple's elements cannot be replaced, but the list inside the tuple can still be modified.

This is an important distinction when working with nested data structures.

Common Beginner Mistakes

• ❌ Trying to modify a tuple element.

• ❌ Forgetting the comma when creating a single-element tuple.

• ❌ Assuming tuples are always faster or better than lists.

• ❌ Confusing tuple unpacking with indexing.

Best Practices

• ✅ Use tuples when the collection represents a fixed set of values.

• ✅ Use lists when the collection needs to change.

• ✅ Choose the data structure based on the behavior you need rather than simply assuming one is better.

Key Takeaways

• A tuple is an ordered, immutable collection.

• Tuples use parentheses by convention, such as (1, 2, 3).

• A single-element tuple requires a trailing comma: (10,).

• Tuples support indexing and slicing.

• Tuple unpacking makes it easy to assign elements to variables.

• Tuples have methods such as count() and index().

• A tuple can contain mutable objects, even though the tuple itself is immutable.

➡️ Double Tap ❤️ For More
👁 2 тыс. ❤ 7👍 2 ↻ 6 7 ноября