0% found this document useful (0 votes)
11 views8 pages

Python Data Structures: Dictionaries & Strings

The document contains a comprehensive set of theory questions, scenario-based questions, and multiple-choice questions (MCQs) focused on dictionaries, structuring data, and manipulating strings in Python. It covers fundamental concepts, practical applications, and testing knowledge on these topics. Each section includes detailed examples and explanations to enhance understanding.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views8 pages

Python Data Structures: Dictionaries & Strings

The document contains a comprehensive set of theory questions, scenario-based questions, and multiple-choice questions (MCQs) focused on dictionaries, structuring data, and manipulating strings in Python. It covers fundamental concepts, practical applications, and testing knowledge on these topics. Each section includes detailed examples and explanations to enhance understanding.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Theory Questions on Dictionaries and Structuring Data

1.​ What is a dictionary in Python? How does it differ from lists and tuples?
2.​ Explain how dictionaries store key-value pairs. Provide an example.
3.​ What are the advantages of using dictionaries over lists?
4.​ How can you add, update, and delete key-value pairs in a dictionary? Provide
examples.
5.​ What are some common dictionary methods? Explain at least five with examples.
6.​ How can you check if a key exists in a dictionary? Provide a Python example.
7.​ What is pretty printing (pprint) in Python? How is it different from regular
printing?
8.​ Explain how dictionaries can be used to model real-world entities. Give an
example.
9.​ What is dictionary comprehension in Python? How can it be used to create a
dictionary dynamically?
10.​How does Python handle dictionary iteration? How can you loop through keys,
values, and key-value pairs?
11.​What are nested dictionaries? How can they be useful in structuring complex
data?
12.​How does the get() method work in dictionaries? Why is it useful?
13.​What happens if you try to access a dictionary key that does not exist? How can
you prevent this error?
14.​Explain the concept of references in dictionaries. What happens when you
assign one dictionary to another?
15.​How can dictionaries be used for counting occurrences of elements in a list?
Provide an example.

Theory Questions on Manipulating Strings

16.​What are strings in Python? How are they different from lists?
17.​How can you declare and initialize a string in Python?
18.​What are some common string methods? Explain at least five with examples.
19.​How does string concatenation work in Python? Provide different ways to
concatenate strings.
20.​What is string replication? How does the * operator work with strings?
21.​Explain string formatting using f-strings, format(), and % formatting.
22.​What is string slicing? How can you extract substrings using indexing?
23.​What are escape characters in Python strings? List some commonly used
escape sequences.
24.​How can you check if a substring exists in a string? Provide a Python example.
25.​Explain how the ord() and chr() functions work in Python.
26.​How can the ord() function be used in encryption and character encoding?
27.​What is the pyperclip module? How is it used for copying and pasting strings?
28.​How can you remove whitespace from a string? Explain methods like strip(),
lstrip(), and rstrip().
29.​What is the difference between split() and join() methods in Python?
30.​Explain the Multi-Clipboard Automatic Messages project. How does it use
pyperclip for automation?

Scenario-Based Questions on Dictionaries and Structuring Data

1.​ Scenario: You are designing an employee database system using dictionaries.
The program should:
○​ Store employee details (name, age, department, salary).
○​ Allow updating an employee’s salary.
○​ Retrieve and display details of an employee by their name.​
Question: Implement this using a Python dictionary and explain how
key-value pairs are useful in storing structured data.
2.​ Scenario: A library management system keeps track of books using a
dictionary where:
○​ The key is the book title, and the value is the availability status
("Available" or "Issued").
○​ Users can check if a book is available.
○​ The system updates the status when a book is issued or returned.​
Question: Write a Python program for this and explain how dictionaries
help in data retrieval.
3.​ Scenario: A student marks system stores student names as keys and their
marks as values in a dictionary.
○​ Allow adding new students and marks.
○​ Calculate the average marks of all students.​
Question: Implement this using dictionaries and explain how iteration
over key-value pairs works.
4.​ Scenario: You are designing a voting system where:
○​ A dictionary stores candidates as keys and their vote counts as values.
○​ When a user votes, the count for the chosen candidate increases.
○​ The program displays the winner at the end.​
Question: Write a Python program for this and explain how dictionaries
efficiently store real-world data.
5.​ Scenario: A supermarket billing system stores product details in a dictionary.
○​ The dictionary contains product names as keys and prices as values.
○​ A user selects products and their quantities.
○​ The program calculates the total bill.​
Question: Implement this and explain how dictionaries simplify data
organization in real-world applications.
Scenario-Based Questions on Manipulating Strings

6.​ Scenario: You are developing a customer feedback system where:


○​ Users enter feedback in the form of a long string.
○​ The system converts the feedback to lowercase and removes extra
spaces.​
Question: Implement this using string methods and explain their
importance in text processing.
7.​ Scenario: A username generator needs to create usernames by:
○​ Taking the first three letters of the user’s first name.
○​ Taking the last three letters of the user’s last name.
○​ Combining them and converting them to lowercase.​
Question: Write a Python program for this and explain how string slicing
helps in automation.
8.​ Scenario: A chatbot needs to detect offensive words and replace them with
***.
○​ The program takes a sentence as input.
○​ It checks for words like "bad", "ugly", and "stupid".
○​ If found, the words are replaced with ***.​
Question: Implement this and explain how the replace() method is
used for content moderation.
9.​ Scenario: You are creating a password strength checker where:
○​ A strong password must contain uppercase letters, lowercase letters,
numbers, and symbols.
○​ The program checks the given password and categorizes it as "Weak",
"Moderate", or "Strong".​
Question: Implement this using string methods and explain how different
checks are applied.
10.​Scenario: You are designing a file renaming tool that:
○​ Takes a filename from the user (e.g., "[Link]").
○​ Converts it to lowercase and replaces spaces with underscores.
○​ Ensures all filenames end with ".txt".​
Question: Write a Python script for this and explain how string methods
help in formatting filenames.
11.​Scenario: You are developing an encryption system where:
○​ Each letter in a message is converted to its ASCII code using ord().
○​ The program prints the encoded message.​
Question: Implement this and explain how ord() is used in
cryptography.
12.​Scenario: A multi-clipboard system stores frequently used messages, such as:
○​ "Hello, how can I help you?"
○​ "Thank you for your message!"
○​ "Please hold on, I will check that for you."
○​ The user selects a message, and the program copies it to the clipboard.​
Question: Implement this using the pyperclip module and explain its
usefulness in automating repetitive tasks.
13.​Scenario: A data validation system requires users to enter an ID in a specific
format:
○​ It must start with "ID-".
○​ It must have exactly five digits after "ID-" (e.g., "ID-12345").​
Question: Implement this using string validation methods and explain
their importance.
14.​Scenario: A word frequency analyzer reads a paragraph and:
○​ Counts how many times each word appears.
○​ Displays the most frequently used words.​
Question: Implement this using dictionaries and explain how counting
operations are handled efficiently.
15.​Scenario: A customer service automation tool stores predefined responses in
a dictionary where:
○​ "hi" maps to "Hello! How can I assist you?".
○​ "help" maps to "Sure! What do you need help with?".
○​ "bye" maps to "Goodbye! Have a great day!".
○​ The user enters a keyword, and the program displays the appropriate
response.​
Question: Write a Python program for this and explain how dictionaries
improve chatbot efficiency.

MCQs on Dictionaries and Structuring Data

1.​ Which of the following correctly defines a dictionary in Python?​


python​
CopyEdit​
a) dict = {1, 2, 3}

b) dict = [1: "one", 2: "two"]

c) dict = {"name": "Alice", "age": 25}

d) dict = (1: "one", 2: "two")

Answer: c) dict = {"name": "Alice", "age": 25}


2.​ What will be the output of the following code?​

my_dict = {"name": "Alice", "age": 25}

print(my_dict.get("city", "Not Found"))

a) "None"​
b) "Not Found"​
c) "city"​
d) Error​
Answer: b) "Not Found"

3.​ What will be the result of the following dictionary operation?​



d = {"a": 1, "b": 2, "c": 3}

print([Link]())

a) ["a", "b", "c"]​


b) dict_keys(["a", "b", "c"])​
c) ["1", "2", "3"]​
d) Error​
Answer: b) dict_keys(["a", "b", "c"])

4.​ Which method is used to remove a specific key-value pair from a dictionary?​
a) delete()​
b) pop()​
c) remove()​
d) discard()​
Answer: b) pop()
5.​ What will be the output of the following Python code?​

my_dict = {"x": 5, "y": 10}

my_dict["x"] += 1

print(my_dict["x"])

a) 5​
b) 6​
c) 10​
d) Error​
Answer: b) 6

MCQs on Manipulating Strings

6.​ What will be the output of the following statement?​



print("hello".upper())

a) "HELLO"​
b) "hello"​
c) "Hello"​
d) Error​
Answer: a) "HELLO"

7.​ What is the output of the following code?​



"Python" + "Programming"

a) "Python Programming"​
b) "PythonProgramming"​
c) "Python + Programming"​
d) Error​
Answer: b) "PythonProgramming"

8.​ What does the strip() method do in Python?​


a) Removes all spaces from a string​
b) Removes leading and trailing whitespace​
c) Converts the string to uppercase​
d) Splits the string into a list​
Answer: b) Removes leading and trailing whitespace
9.​ What is the function of ord("A") in Python?​
a) Returns the ASCII value of "A"​
b) Converts "A" to lowercase​
c) Returns "A" as a Unicode string​
d) Reverses the string "A"​
Answer: a) Returns the ASCII value of "A"
10.​What does the chr(65) function return?​
a) "A"​
b) 65​
c) "B"​
d) Error​
Answer: a) "A"
11.​What is the purpose of the pyperclip module?​
a) To copy and paste text between programs​
b) To read files from disk​
c) To format strings​
d) To generate random numbers​
Answer: a) To copy and paste text between programs

12.​What will be the output of the following Python code?​



s = "Hello, World!"

print([Link]("World", "Python"))

a) "Hello, Python!"​
b) "Hello, World!"​
c) "Hello Python"​
d) "Hello, World"​
Answer: a) "Hello, Python!"

13.​What will be the result of the following statement?​


"Hello".find("e")

a) 1​
b) 0​
c) -1​
d) "e"​
Answer: a) 1

14.​What will the following code output?​



import pyperclip

[Link]("Hello")

print([Link]())

a) "Hello"​
b) None​
c) Error​
d) Empty String​
Answer: a) "Hello"

15.​What will be the output of the following Python statement?​


print("hello".capitalize())

a) "hello"​
b) "Hello"​
c) "HELLO"​
d) "hELLO"​
Answer: b) "Hello"

Common questions

Powered by AI

The get() method in dictionaries allows safe access to values associated with keys, providing a default value if the key does not exist, which prevents KeyErrors that would otherwise occur if a nonexistent key were accessed using `dict[key]`. For instance, `my_dict.get('key', 'default')` returns the value of 'key' if it exists, or 'default' if it doesn't, ensuring the program continues smoothly without exceptions. This method enhances code robustness, especially in large datasets where key presence might vary or not be guaranteed .

Lists of tuples lack the O(1) average time complexity that dictionaries offer for access operations due to their reliance on index-based access rather than direct key access. Updating an element within a list of tuples requires iterating through the list to identify the correct tuple and then reconstructing the tuple to update the value. In contrast, dictionaries allow direct access and update through unique keys. This inefficiency in lists makes them less suitable for applications where frequent updates are required, as performing these operations entails more computational overhead and complexity, especially as the data size increases .

In a library management system, key-value pairs in dictionaries allow for concise and efficient mapping between book titles and their availability status. Each book title serves as a unique key, while the availability status (e.g., 'Available' or 'Issued') serves as the value. This mapping enables O(1) average time complexity for checking a book's availability, updating its status, or retrieving the current state of the library. Such efficiency is crucial for real-time operations and quick user responses . Furthermore, the system's flexibility with key-value pairs also supports future extensions, such as including additional metadata like author or genre without altering the underlying data structure significantly.

String slicing allows specific segments of a string to be extracted, which is crucial for creating automated and consistent outputs, such as usernames. In a username generator, slicing can be used to extract the first three letters from a user's first name and the last three from their last name. This process involves using slicing syntax, such as `first_name[:3]` and `last_name[-3:]`, to selectively capture parts of the strings. By automating these extractions and combining them (e.g., `username = (first_three + last_three).lower()`), the program efficiently creates a username without manual intervention, enhancing reliability and speed in operations where uniformity and batch processing are essential .

The replace() method is pivotal in chatbots for moderating content by substituting offensive words with non-offensive placeholders like asterisks. Using `sentence.replace('offensive_word', '***')`, chatbots scan and transform inputs containing flagged expressions (e.g., 'bad', 'ugly', 'stupid') into sanitized outputs, ensuring user interactions remain respectful and safe. By dynamically adapting through lists of prohibited words, the method supports real-time moderation without the need for complex processing or delays, maintaining the application's responsiveness while adhering to community guidelines and ethical communication standards .

Nested dictionaries are powerful for structuring hierarchical data, enabling the representation of complex entities with sub-elements. For instance, in an employee management system, each employee entry (the key) could map to a dictionary storing keys such as personal details, job details, and contact information, each potentially further nesting data (e.g., contact splitting into email and phone). This hierarchy allows data to be compartmentalized, making it easier to manage, query, and modify specific aspects without affecting the entire structure. This nested approach mirrors real-world scenarios where objects have multiple layers of attributes, thus aiding in data organization, scalability, and better alignment with models like JSON for web-based applications .

Dictionaries provide a key-value pair structure that allows for easy and quick data access, updates, and deletions using keys. In an employee database, each employee can have a dictionary key (such as an employee ID or name) pointing to a nested dictionary storing details like age, department, and salary. Lists, on the other hand, are best suited for ordered data that can be accessed using indices, which may not be as intuitive or efficient for updating or retrieving employee records by name or ID. Moreover, dictionaries offer O(1) time complexity for lookups, make operations quicker than accessing elements in lists, especially as the dataset grows .

The pyperclip module is integral for clipboard operations, enabling text to be programmatically copied and pasted across systems. In multi-clipboard systems, pyperclip facilitates the storage and retrieval of frequently used messages, allowing users to quickly paste standardized responses without manual copying. By automating these tasks, it significantly reduces user input time and errors in repetitive tasks, enhancing productivity. For example, `pyperclip.copy(text)` and `pyperclip.paste()` manage clipboard content seamlessly, supporting tasks like customer service where consistency and speed are critical . Such automation is essential in environments requiring high-volume communication and standardized interactions, offering a straightforward integration with scripting languages.

Ensuring the presence of diverse character types—uppercase, lowercase, numbers, and symbols—in passwords increases their complexity and reduces vulnerability to attacks such as brute force or dictionary attacks. Each character type adds a separate dimension to the password's character space, exponentially increasing the combination possibilities. For instance, requiring symbols adds 32 additional characters from the ASCII table to the character set. A checker program uses methods like `any(c.isupper() for c in password)` for uppercase checks, thus categorizing passwords into 'Weak', 'Moderate', or 'Strong' based on such criteria. This stratification helps educate users on creating secure passwords, crucial in maintaining privacy and data integrity .

Dictionary comprehension provides a concise and readability-enhanced way to construct dictionaries in Python. It allows the creation of dictionaries by iterating over an iterable, applying conditions, and specifying key-value pairs in a single, often compact line of code. For example, `{k: v for k, v in zip(keys, values)}` quickly creates a dictionary from paired lists of keys and values. This method is advantageous for its expressiveness and ability to incorporate logic directly within the comprehension, like filtering or transforming data, making code shorter and often more performant than using traditional loops with assignments. Additionally, it aligns with Python's ethos of readability and efficiency .

You might also like