Python Dictionary

Dictionaries declaration and operations in Python.

Python - Dictionary:

Python dictionaries are a built-in data type used to store key-value pairs. They are mutable, unordered collections of items where each item is a pair consisting of a key and a value. Dictionaries are extremely versatile and commonly used in Python for various purposes due to their flexibility and efficiency in retrieving, adding, and modifying elements.

Overview of how dictionaries work in Python:

1. Creating a Dictionary: You can create a dictionary by enclosing a comma-separated list of key-value pairs within curly braces '{}'. Keys must be unique and immutable (such as strings, numbers, or tuples), while values can be of any data type.

my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}

2. Accessing Values: You can access the values in a dictionary using square brackets '[]' along with the key.

mixed_list = [1, "hello", 3.14, True]

3. Adding or Modifying Entries: You can add new key-value pairs or modify existing ones using square brackets '[]'.

my_dict['new_key'] = 'new_value'
my_dict['key1'] = 'modified_value'

4. Removing Entries: You can remove a key-value pair from a dictionary using the del statement or the 'pop()' method.

my_dict['new_key'] = 'new_value'
my_dict['key1'] = 'modified_value'

5. Dictionary Methods: Python dictionaries come with several built-in methods for performing various operations such as getting all keys, all values, or all items.

keys = my_dict.keys()
values = my_dict.values()
items = my_dict.items()

6. Looping through a Dictionary: You can iterate over the keys, values, or items of a dictionary using a 'for' loop.

for key in my_dict:
    print(key, my_dict[key])

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

7. Dictionary Comprehension: Like lists, Python dictionaries also support comprehension for creating dictionaries in a more concise way.

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

8. Nested Dictionaries: You can have dictionaries as values in a dictionary, allowing you to represent more complex data structures.

nested_dict = {'dict1': {'key1': 'value1'}, 'dict2': {'key2': 'value2'}}

Let's create a simple Python program that demonstrates the use of dictionaries. This program will be a basic contact book where users can add contacts, view contacts, and search for contacts by name.

PDF Copy Code
# Function to add a contact to the contact book
def add_contact(contact_book):
    name = input("Enter the name of the contact: ")
    number = input("Enter the phone number: ")
    contact_book[name] = number
    print("Contact added successfully!")

# Function to view all contacts in the contact book
def view_contacts(contact_book):
    if contact_book:
        print("Contacts:")
        for name, number in contact_book.items():
            print(f"{name}: {number}")
    else:
        print("No contacts found.")

# Function to search for a contact by name
def search_contact(contact_book):
    name = input("Enter the name of the contact to search: ")
    if name in contact_book:
        print(f"Phone number of {name}: {contact_book[name]}")
    else:
        print(f"No contact found with the name {name}.")

# Main function
def main():
    contact_book = {}
    while True:
        print("\nMenu:")
        print("1. Add Contact")
        print("2. View Contacts")
        print("3. Search Contact")
        print("4. Exit")
        choice = input("Enter your choice: ")

        if choice == '1':
            add_contact(contact_book)
        elif choice == '2':
            view_contacts(contact_book)
        elif choice == '3':
            search_contact(contact_book)
        elif choice == '4':
            print("Exiting the program.")
            break
        else:
            print("Invalid choice. Please try again.")

if __name__ == "__main__":
    main()
Output:
Menu:
1. Add Contact     
2. View Contacts   
3. Search Contact  
4. Exit
Enter your choice: 1
Enter the name of the contact: Ayan
Enter the phone number: +111-11103482
Contact added successfully!

This program defines four functions:

1. 'add_contact': Adds a new contact to the contact book.

2. 'view_contacts': Displays all contacts stored in the contact book.

3. 'search_contact': Searches for a contact by name and displays their phone number.

4. 'main': The main function where the program flow starts. It presents a menu to the user and calls the appropriate function based on the user's choice.

Python dictionaries are fundamental data structures in the language and are widely used in various programming tasks, including data manipulation, configuration settings, and more.

What's Next?

We've now entered the finance section on this platform, where you can enhance your financial literacy.