Dictionary

Top 10 Python examples using Dictionaries to learn easily

The dictionary type in Python is a mutable, unordered collection of key-value pairs, where each key must be unique within the collection. Dictionaries are used to store data values in a way that makes it easy to reference and look up values based on their associated keys. They are defined by enclosing a comma-separated sequence of key-value pairs in curly braces {}. Following are Python examples using Dictionaries:

Dictionary

Example 1: Counting Word Occurrences

Description: This example demonstrates how to count the occurrences of words in a given text using a dictionary.

def count_word_occurrences(text):
    words = text.split()
    word_count = {}

    for word in words:
        word = word.lower()
        if word in word_count:
            word_count[word] += 1
        else:
            word_count[word] = 1

    return word_count

text = "This is a sample text. This text is just an example."
word_occurrences = count_word_occurrences(text)
print(word_occurrences)

Example 2: Merging Dictionaries

Description: This example shows how to merge two dictionaries while resolving key conflicts.

dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
merged_dict = {**dict1, **dict2}
print(merged_dict)

Example 3: Creating a Frequency Dictionary

Description: This example creates a dictionary to store the frequency of numbers in a given list.

numbers = [1, 2, 3, 2, 1, 3, 4, 5, 2]
frequency_dict = {}
for num in numbers:
    if num in frequency_dict:
        frequency_dict[num] += 1
    else:
        frequency_dict[num] = 1
print(frequency_dict)

Example 4: Finding Common Elements.

Description: This example finds common elements between two lists using set comprehension.

list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]
common_elements = {x for x in list1 if x in list2}
print(common_elements)

Example 5: Grouping Items by Category

Description: This example groups items by category using a dictionary.

items = [
    {'name': 'apple', 'category': 'fruit'},
    {'name': 'carrot', 'category': 'vegetable'},
    {'name': 'banana', 'category': 'fruit'}
]
category_dict = {}
for item in items:
    category = item['category']
    if category in category_dict:
        category_dict[category].append(item['name'])
    else:
        category_dict[category] = [item['name']]
print(category_dict)

Example 6: Nested Dictionaries

Description: This example showcases nested dictionaries to store information about students.

students = {
    'Alice': {'age': 20, 'grade': 'A'},
    'Bob': {'age': 19, 'grade': 'B'}
}
print(students['Alice']['age'])

Example 7: Removing Key-Value Pairs

Description: This example demonstrates how to remove a key-value pair from a dictionary.

person = {'name': 'John', 'age': 30, 'city': 'New York'}
if 'age' in person:
    del person['age']
print(person)

Example 8: Dictionary Comprehension

Description: This example uses dictionary comprehension to create a dictionary of squares.

squares = {x: x**2 for x in range(1, 6)}
print(squares)

Example 9: Default Dictionary Values

Description: This example uses a defaultdict to create a dictionary with default integer values for counting.

from collections import defaultdict

fruit_counter = defaultdict(int)
fruits = ['apple', 'banana', 'apple', 'orange', 'banana']
for fruit in fruits:
    fruit_counter[fruit] += 1
print(dict(fruit_counter))

Example 10: Dictionary Methods

Description: This example showcases various dictionary methods, including update, get, keys, and values.

contacts = {'Alice': '123-456-7890', 'Bob': '987-654-3210'}
contacts.update({'Eve': '555-555-5555'})
print(contacts.get('Alice'))
print(contacts.keys())
print(contacts.values())

These examples cover a range of tasks you can perform using dictionaries in Python.

Read also: