Here's an example of a simple dictionary in Python:

person = {'name': 'Alice', 'age': 25, 'occupation': 'Software Engineer'}

This dictionary contains three key-value pairs: 'name', 'age', and 'occupation'. Now, let's say we want to add a new key-value pair to this dictionary. We can do that like this:

person['location'] = 'San Francisco'

And now our dictionary looks like this:

{'name': 'Alice', 'age': 25, 'occupation': 'Software Engineer', 'location': 'San Francisco'}

In JavaScript, the same object would look like this:

const person = {name: 'Alice', age: 25, occupation: 'Software Engineer'};

To add a new property, we can do this:

person.location = 'San Francisco';

And our object will now look like this:

{name: 'Alice', age: 25, occupation: 'Software Engineer', location: 'San Francisco'}

Common operations and use cases for dictionaries

Dictionaries are like the Swiss Army Knife of data structures - they're incredibly versatile and can be used in a wide range of applications.

In Python, common operations and use cases for dictionaries include storing and retrieving data, counting occurrences of items, grouping items by category, and mapping one set of data to another.

Let's explore these operations and use cases in more detail.

Storing and Retrieving Data One of the most basic uses for a dictionary is to store and retrieve data. This is similar to the way you might use a dictionary to look up a word and find its definition. For example:

person = {'name': 'John', 'age': 35, 'city': 'New York'} print(person['name'])

This code creates a dictionary called 'person' and retrieves the value associated with the key 'name', which is 'John'.

Counting Occurrences of Items Dictionaries can also be used to count the occurrences of items in a list. For example:

fruits = ['apple', 'banana', 'orange', 'apple', 'orange', 'banana', 'apple'] fruit_counts = {} for fruit in fruits: if fruit in fruit_counts: fruit_counts[fruit] += 1 else: fruit_counts[fruit] = 1 print(fruit_counts)

This code creates a dictionary called 'fruit_counts' and counts the number of times each fruit appears in the 'fruits' list. The resulting dictionary looks like this:

{'apple': 3, 'banana': 2, 'orange': 2}

Grouping Items by Category Dictionaries can also be used to group items by category. For example:

students = [{'name': 'Alice', 'grade': 'A'}, {'name': 'Bob', 'grade': 'B'}, {'name': 'Charlie', 'grade': 'A'}] grades = {} for student in students: grade = student['grade'] if grade in grades: grades[grade].append(student['name']) else: grades[grade] = [student['name']] print(grades)

This code creates a dictionary called 'grades' and groups the students by their grade. The resulting dictionary looks like this:

{'A': ['Alice', 'Charlie'], 'B': ['Bob']}

Mapping One Set of Data to Another Dictionaries can also be used to map one set of data to another. For example:

Python Programming for Lazy Beginners: A Simple and Easy TutorialWhere stories live. Discover now