Summary

This document introduces Python dictionaries, a data structure for storing key-value pairs. It includes examples and explanations about types of dictionaries, access methods, modifications, and using dictionaries for different tasks. The information is suitable for students learning python programming.

Full Transcript

UNIT3: Python Dictionaries Introduction to Dictionaries  A dictionary in Python is an unordered collection of key-value pairs.  It allows you to store data in a way that each item has a unique key that is associated with a value.  Python dictionaries are mutable, meaning their con...

UNIT3: Python Dictionaries Introduction to Dictionaries  A dictionary in Python is an unordered collection of key-value pairs.  It allows you to store data in a way that each item has a unique key that is associated with a value.  Python dictionaries are mutable, meaning their contents can be changed after they are created.  Syntax: Dictionaries are enclosed in curly braces {}, with key-value pairs separated by a colon : Example of creating a dictionary my_dict = {'name': 'John', 'age': 30, 'city': 'New York'} Types of Dictionaries Empty Dictionary: my_dict = {} Dictionary with Integer Elements: my_dict = {1: 'apple', 2: 'banana', 3: 'cherry'} Dictionary with Mixed Data Types: my_dict = {1: 'apple', 'name': 'John', 3.14: 3.14} Nested Dictionary: A dictionary inside another dictionary. my_dict = {"person": {"name": "John", "age": 30}, "address": "New York"} Single Element Dictionary: my_dict = {1: 'apple'} Using dict() Constructor: my_dict = dict(key='value', number=42) PYTHON UNIT3(DICTIONARY) | ARPITHA TODO: Accessing Dictionary Elements Using Keys: You can access dictionary elements by referencing their key inside square brackets []. my_dict = {1: 'apple', 2: 'banana', 3: 'cherry'} print(my_dict) print(my_dict) Using get() Method: The get() method returns the value associated with a specified key, and does not raise an error if the key doesn’t exist (returns None by default). print(my_dict.get(2)) print(my_dict.get(4)) Accessing Nested Dictionaries: my_dict = {"person": {"name": "John", "age": 30}, "address": "New York"} print(my_dict["person"]["name"]) Using in Keyword: Check if a key exists in the dictionary. if 1 in my_dict: print("Key 1 exists") Modifying Dictionaries Adding Items: You can add new key-value pairs to a dictionary. my_dict = {1: 'apple', 2: 'banana'} my_dict = 'cherry' print(my_dict) Changing Values: Modify the value of an existing key. my_dict = 'orange' print(my_dict) PYTHON UNIT3(DICTIONARY) | ARPITHA Removing Items: Using del: del my_dict # Removes the item with key 1 print(my_dict Using pop() to remove and return the value: removed_item = my_dict.pop(2) print(removed_item) print(my_dict) Clearing the Dictionary: my_dict.clear() # Removes all items print(my_dict) Deleting the Entire Dictionary: del my_dict # print(my_dict) Dictionary Methods keys(): Returns a view object displaying all the keys. print(my_dict.keys()) values(): Returns a view object displaying all the values. print(my_dict.values()) items(): Returns a view object displaying key-value pairs as tuples. print(my_dict.items()) get(): Returns the value of a given key. print(my_dict.get(1)) print(my_dict.get(5)) popitem(): Removes and returns an arbitrary key-value pair. print(my_dict.popitem()) PYTHON UNIT3(DICTIONARY) | ARPITHA update(): Updates the dictionary with elements from another dictionary or an iterable of key-value pairs. my_dict.update print(my_dict) Iterating Through a Dictionary You can loop through a dictionary in various ways: my_dict ={1: 'apple', 2: 'orange', 3: 'cherry'} Iterate through keys: for key in my_dict: print(key) Iterate through values: for value in my_dict.values(): print(value) Iterate through key-value pairs: for key, value in my_dict.items(): print(key, value) Dictionary Length To get the number of key-value pairs in a dictionary, use the len() function: print(len(my_dict)) Example Programs for Dictionaries Add an Item to a Dictionary: my_dict = {1: 'apple', 2: 'banana'} my_dict = 'cherry' print(my_dict) Convert a Tuple of Characters to a Dictionary: tup = ('a', 'b', 'c') PYTHON UNIT3(DICTIONARY) | ARPITHA dict_from_tuple = {i: i.upper() for i in tup} print(dict_from_tuple) Find the Frequency of Each Element in a Dictionary: my_dict = {'apple': 2, 'banana': 3, 'cherry': 1} print(my_dict['banana']) Replace a Specific Key in a Dictionary: my_dict = {'a': 1, 'b': 2, 'c': 3} my_dict['a'] = 100 print(my_dict) } Merge Two Dictionaries: dict1 = {'apple': 1, 'banana': 2} dict2 = {'cherry': 3, 'date': 4} dict1.update(dict2) print(dict1) Advantages of Using Dictionaries Over Lists Faster Lookups: Dictionaries provide faster lookups (average O(1) time complexity), while lists require a linear scan (O(n)). Key-Value Pairs: Dictionaries are ideal for associating values with specific keys, unlike lists that only store values in an ordered sequence. Mutable: Dictionaries are mutable, meaning you can change values directly without creating a new object, unlike tuples or strings. Flexible Keys: Keys in dictionaries can be of any immutable type (e.g., strings, numbers, tuples), while lists require elements to be indexed by integers. 1. Dictionaries as a Set of Counters A dictionary can be used to keep track of the frequency of elements (i.e., counts). This is particularly useful when counting occurrences in a list, string, or file. PYTHON UNIT3(DICTIONARY) | ARPITHA Example: Write a function that takes a sentence as input and counts the frequency of each word in the sentence. Return a dictionary where the keys are the words and the values are the counts. # List of items my_list = ['apple', 'banana', 'apple', 'orange', 'banana', 'banana'] count_dict = {} for item in my_list: if item in count_dict: count_dict[item] += 1 else: count_dict[item] = 1 print(count_dict) # Output: {'apple': 2, 'banana': 3, 'orange': 1 TODO: Question 1: Count Occurrences of Each Word in a Sentence Problem: Write a function that takes a sentence as input and counts the frequency of each word. Return a dictionary where the keys are the words and the values are the counts. Expected Output: For input "Hello world, hello again, world!" {'hello': 2, 'world,': 2, 'again,': 1} Question 2: Count Occurrences of Characters in a String Problem: Write a function that counts how many times each character appears in a given string. Return the result in a dictionary. Expected Output: For input "hello" {'h': 1, 'e': 1, 'l': 2, 'o': 1} 2. Dictionaries and Files PYTHON UNIT3(DICTIONARY) | ARPITHA Dictionaries can be useful for working with files, especially for tasks like processing data, counting occurrences, or organizing data in key-value pairs. Question 1: Count the Frequency of Words in a Text File Problem: Write a program that reads a file named textfile.txt, counts the occurrences of each word (case-insensitive), and stores the results in a dictionary. Expected Output: For a file textfile.txt with the following content: Hello world. Hello Python. Python is fun. Hello again. The output would be: {'hello': 3, 'world.': 1, 'python.': 2, 'is': 1, 'fun.': 1, 'again.': 1} Code: # Open a file for reading with open('textfile.txt', 'r') as file: word_count = {} for line in file: words = line.split() for word in words: word = word.lower() # Convert to lowercase for case-insensitive counting if word in word_count: word_count[word] += 1 else: word_count[word] = 1 print(word_count) TODO: Question 2: Count the Frequency of Letters in a Text File Problem: Write a program that reads a file named letters.txt and counts the occurrences of each letter (case-insensitive) in the file, ignoring spaces and punctuation. Store the results in a dictionary. Expected Output: For a file letters.txt with the following content: PYTHON UNIT3(DICTIONARY) | ARPITHA Hello, World! Python is fun. The output would be: {'h': 1, 'e': 1, 'l': 3, 'o': 2, 'w': 1, 'r': 1, 'd': 1, 'p': 1, 'y': 1, 't': 1, 'n': 1, 'i': 1, 's': 1, 'f': 1, 'u': 1} Question 3: Count the Frequency of Specific Words in a File Problem: Write a program that reads a file named input.txt and counts the occurrences of specific words (given in a list) in the file. The results should be stored in a dictionary where the keys are the words from the list, and the values are their counts. Expected Output: For a file input.txt with the following content: Python is a powerful programming language. Python is popular. And a list of words to search for: ['python', 'is', 'programming', 'language'] The output would be: {'python': 2, 'is': 2, 'programming': 1, 'language': 1} Question 4: Count Word Frequencies Using a Loop and a Dictionary Problem: Write a program that reads a file named sample.txt, counts the occurrences of each word, and stores the result in a dictionary. Use loops to iterate through the file and update the dictionary. Expected Output: For a file sample.txt with the content: apple orange banana apple orange apple banana orange apple The output would be: {'apple': 4, 'orange': 3, 'banana': 2} PYTHON UNIT3(DICTIONARY) | ARPITHA 3. Looping and Dictionaries Looping through dictionaries is essential when you need to process data in each key-value pair. You can loop through just the keys, just the values, or both keys and values. Example: Iterating through Keys, Values, and Key-Value Pairs my_dict = {'apple': 2, 'banana': 3, 'cherry': 1} for key in my_dict: print(key) for value in my_dict.values(): print(value) for key, value in my_dict.items(): print(key, value) Example: Looping with Conditional Logic for key, value in my_dict.items(): if value > 2: print(f"{key}: {value}") 4. Advanced Text Parsing with Dictionaries Dictionaries are particularly useful for parsing and analyzing text. You can store and manipulate data from text, such as replacing certain words, extracting named entities, or performing frequency analysis. Example: Extracting Word Frequency from a Large Text (Advanced Parsing) import re text = "Hello world. Python is amazing. Hello Python world." # Using regex to extract words and count frequencies words = re.findall(r'\w+', text.lower()) # \w+ matches words word_count = {} PYTHON UNIT3(DICTIONARY) | ARPITHA for word in words: if word in word_count: word_count[word] += 1 else: word_count[word] = 1 print(word_count) # Output: {'hello': 2, 'world': 2, 'python': 2, 'is': 1, 'amazing': 1} Assignment 1. Word Frequency Counter Question: Write a Python program to count the frequency of each word in the following text: "Hello world, hello Python! Welcome to the world of Python." The program should output the count of each word, ignoring case and punctuation. Hint: Split the text into words and use a dictionary to store and count the occurrences. 2. Adding and Updating Key-Value Pairs Question: Create a dictionary with two items:  'apple': 2  'banana': 3 Then:  Update the value for 'apple' to 5.  Add a new item with the key 'orange' and value 1. Print the updated dictionary. 3. Finding the Maximum Value in a Dictionary PYTHON UNIT3(DICTIONARY) | ARPITHA Question: Given the following dictionary: {'apple': 2, 'banana': 3, 'cherry': 5} Write a Python program to find the key with the maximum value. Your program should return the key and its corresponding value. 4. Iterating Through a Dictionary Question: Write a Python program that: 1. Iterates through the keys of a dictionary and prints each key. 2. Iterates through the values of the dictionary and prints each value. 3. Iterates through the key-value pairs of the dictionary and prints each key with its corresponding value. Use the following dictionary as an example: {'apple': 2, 'banana': 3, 'cherry': 5} 5. Removing Items from a Dictionary Question: Given the dictionary: {'apple': 2, 'banana': 3, 'cherry': 5} 1. Write a program to remove the key 'banana' using the del statement. 2. Write a program to remove the key 'cherry' using the pop() method. 3. After each removal, print the updated dictionary. 6. Simple Text Parsing: Find All Capitalized Words Question: Write a Python program that extracts and counts all capitalized words from the following text: "Alice and Bob are friends. Alice likes Python, and Bob likes Java." Store the capitalized words in a dictionary and print the count of each capitalized word. PYTHON UNIT3(DICTIONARY) | ARPITHA 7. Merging Two Dictionaries Question: Given two dictionaries: dict1 = {'apple': 1, 'banana': 2} dict2 = {'cherry': 3, 'date': 4} Write a program to merge these two dictionaries into a single dictionary. Print the merged dictionary. 8. Converting a List of Tuples to a Dictionary Question: You are given the following list of tuples: [('apple', 1), ('banana', 2), ('cherry', 3)] Write a Python program to convert this list into a dictionary. Print the resulting dictionary. 9. Frequency of Each Element in a Dictionary Question: Create a dictionary to store the frequency of fruits: fruits = {'apple': 2, 'banana': 3, 'cherry': 1} Write a program to find the frequency of the fruit 'banana' in the dictionary. Print the frequency. NOTE :  Todo questions to be written in classwork and Assignment questions to be written in assignment book PYTHON UNIT3(DICTIONARY) | ARPITHA

Use Quizgecko on...
Browser
Browser