VOOZH about

URL: https://www.analyticsvidhya.com/blog/2024/02/mcqs-on-python-dictionary-manipulation/

⇱ 30+ MCQs on Python Dictionary Manipulation


India's Most Futuristic AI Conference Is Back – Bigger, Sharper, Bolder

  • d
  • :
  • h
  • :
  • m
  • :
  • s

30+ MCQs on Python Dictionary Manipulation

Ayushi Trivedi Last Updated : 06 Mar, 2024
9 min read

Welcome to the Python Dictionary Manipulation Python Interview Questions Dictionaries are versatile data structures in Python, allowing you to store key-value pairs and perform various operations such as adding, removing, updating, and accessing elements efficiently. These questions will test your understanding of various dictionary manipulation techniques, including methods for adding and removing items, accessing values by keys, checking for key existence, and more. Each question is multiple-choice, with only one correct answer. Take your time to carefully read each question and choose the best option. Let’s explore the world of Python dictionary manipulation together!

πŸ‘ Python Dictionary Manipulation

30+ Python Interview Questions on Python Dictionary Manipulation

Q1. What does the pop() method do when used on a Python dictionary?

a) Removes and returns the last item of the dictionary

b) Removes and returns the item with the specified key

c) Removes and returns the item at the specified index

d) Removes and returns the first item of the dictionary

Answer: b

Explanation: The pop() method removes and returns the item with the specified key from the dictionary.

Q2. Which of the following methods is used to add a new key-value pair to a Python dictionary?

a) add()

b) insert()

c) append()

d) None of the above

Answer: d

Explanation: There is no add() or insert() method for dictionaries. New key-value pairs are added using assignment, e.g., my_dict['new_key'] = 'value'.

Q3. What will be the output of the following Python code snippet?

my_dict = {'a': 1, 'b': 2, 'c': 3}
result = my_dict.get('b', 0)
print(result)

a) 1

b) 2

c) 3

d) 0

Answer: b

Explanation: The get() method returns the value of the specified key. If the key is not found, it returns the default value, which is 0 in this case.

Q4. Which of the following methods is used to get a list of all keys in a Python dictionary?

a) keys()

b) get_keys()

c) list()

d) None of the above

Answer: a

Explanation: The keys() method returns a view object that displays a list of all the keys in the dictionary.

Q5. What will be the output of the following Python code snippet?

my_dict = {'a': 1, 'b': 2, 'c': 3}
result = my_dict.keys()
print(result)

a) [β€˜a’, β€˜b’, β€˜c’]

b) (β€˜a’, β€˜b’, β€˜c’)

c) dict_keys([β€˜a’, β€˜b’, β€˜c’])

d) {β€˜a’, β€˜b’, β€˜c’}

Answer: c

Explanation: The keys() method returns a dict_keys object that contains the keys of the dictionary.

Q6. Which of the following methods is used to get a list of all values in a Python dictionary?

a) values()

b) get_values()

c) list()

d) None of the above

Answer: a

Explanation: The values() method returns a view object that displays a list of all the values in the dictionary.

Q7. What will be the output of the following Python code snippet?

my_dict = {'a': 1, 'b': 2, 'c': 3}
result = my_dict.values()
print(result)

a) [1, 2, 3]

b) (1, 2, 3)

c) dict_values([1, 2, 3])

d) {1, 2, 3}

Answer: c

Explanation: The values() method returns a dict_values object that contains the values of the dictionary.

Q8. Which of the following methods is used to get a list of all key-value pairs in a Python dictionary?

a) items()

b) get_items()

c) list()

d) None of the above

Answer: a

Explanation: The items() method returns a view object that displays a list of tuples containing the key-value pairs in the dictionary.

Q9. What will be the output of the following Python code snippet?

my_dict = {'a': 1, 'b': 2, 'c': 3}
result = my_dict.items()
print(result)

a) [(β€˜a’, 1), (β€˜b’, 2), (β€˜c’, 3)]

b) ((β€˜a’, 1), (β€˜b’, 2), (β€˜c’, 3))

c) dict_items([(β€˜a’, 1), (β€˜b’, 2), (β€˜c’, 3)])

d) {(β€˜a’, 1), (β€˜b’, 2), (β€˜c’, 3)}

Answer: c

Explanation: The items() method returns a dict_items object that contains the key-value pairs of the dictionary as tuples.

Q10. Which of the following methods is used to remove a key-value pair from a Python dictionary?

a) remove()

b) delete()

c) pop()

d) None of the above

Answer: c

Explanation: The pop() method removes the specified key and returns the corresponding value from the dictionary.

Q11. What will be the output of the following Python code snippet?

my_dict = {'a': 1, 'b': 2, 'c': 3}
result = my_dict.pop('b')
print(result)

a) 1

b) 2

c) 3

d) {β€˜a’: 1, β€˜c’: 3}

Answer: b

Explanation: The pop() method removes the key β€˜b’ from the dictionary and returns its corresponding value.

Q12. Which of the following methods is used to clear all items from a Python dictionary?

a) clear()

b) delete_all()

c) remove_all()

d) None of the above

Answer: a

Explanation: The clear() method removes all items from the dictionary.

Q13. What will be the output of the following Python code snippet?

my_dict = {'a': 1, 'b': 2, 'c': 3}
my_dict.clear()
print(my_dict)

a) {}

b) {β€˜a’: 1, β€˜b’: 2, β€˜c’: 3}

c) []

d) None

Answer: a

Explanation: The clear() method removes all items from the dictionary, leaving it empty.

Q14. Which of the following methods is used to update a Python dictionary with elements from another dictionary or from an iterable of key-value pairs?

a) merge()

b) update()

c) append()

d) extend()

Answer: b

Explanation: The update() method updates the dictionary with elements from another dictionary object or from an iterable of key-value pairs.

Q15. What will be the output of the following Python code snippet?

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

a) {β€˜a’: 1, β€˜b’: 2, β€˜c’: 4}

b) {β€˜a’: 1, β€˜b’: 3, β€˜c’: 4}

c) {β€˜a’: 1, β€˜b’: 3}

d) {β€˜a’: 1, β€˜b’: 2, β€˜c’: 3}

Answer: b

Explanation: The update() method updates dict1 with the key-value pairs from dict2, overwriting values for keys that already exist in dict1.

Q16. Which of the following statements about dictionaries in Python is true?

a) Dictionaries are ordered collections

b) Dictionaries can contain duplicate keys

c) Dictionaries are indexed by integers

d) Dictionaries are immutable

Answer: b

Explanation: Dictionaries in Python can have duplicate keys, but each key is unique within the dictionary.

Q17. What will be the output of the following Python code snippet?

my_dict = {'a': 1, 'b': 2, 'c': 3}
result = my_dict.popitem()
print(result)

a) (β€˜a’, 1)

b) (β€˜b’, 2)

c) (β€˜c’, 3)

d) {β€˜a’: 1, β€˜b’: 2}

Answer: c

Explanation: The popitem() method removes and returns the last inserted key-value pair from the dictionary.

Q18. Which of the following methods is used to get the value for a specified key in a Python dictionary, and if the key does not exist, it inserts the key with the specified default value?

a) get_or_insert()

b) setdefault()

c) find_or_insert()

d) None of the above

Answer: b

Explanation: The setdefault() method returns the value of the specified key, and if the key does not exist, it inserts the key with the specified default value.

Q19. What will be the output of the following Python code snippet?

my_dict = {'a': 1, 'b': 2, 'c': 3}
result = my_dict.setdefault('d', 4)
print(result)

a) 1

b) 2

c) 3

d) 4

Answer: d

Explanation: Since β€˜d’ does not exist in my_dict, setdefault() inserts the key β€˜d’ with the value 4 and returns 4.

Q20. Which of the following methods is used to get the value for a specified key in a Python dictionary?

a) find()

b) get()

c) retrieve()

d) None of the above

Answer: b

Explanation: The get() method returns the value for the specified key in the dictionary.

Q21. What will be the output of the following Python code snippet?

my_dict = {'a': 1, 'b': 2, 'c': 3}
result = my_dict.get('b', 0)
print(result)

a) 1

b) 2

c) 3

d) 0

Answer: b

Explanation: The get() method returns the value of the specified key. If the key is not found, it returns the default value, which is 0 in this case.

Q22. Which of the following methods is used to check if a key exists in a Python dictionary?

a) check()

b) exists()

c) in operator

d) None of the above

Answer: c

Explanation: The in operator can be used to check if a key exists in a dictionary.

Q23. What will be the output of the following Python code snippet?

my_dict = {'a': 1, 'b': 2, 'c': 3}
result = 'a' in my_dict
print(result)

a) True

b) False

c) 1

d) Error

Answer: a

Explanation: The in operator checks if β€˜a’ exists as a key in the dictionary, which it does, so the output is True.

Q24. What will be the output of the following Python code snippet?

my_dict = {'a': 1, 'b': 2, 'c': 3}
new_dict = my_dict.copy()
new_dict['d'] = 4
print(my_dict)

a) {β€˜a’: 1, β€˜b’: 2, β€˜c’: 3}

b) {β€˜a’: 1, β€˜b’: 2, β€˜c’: 3, β€˜d’: 4}

c) {β€˜a’: 1, β€˜b’: 2, β€˜c’: 3, β€˜d’: 4}

d) {β€˜a’: 1, β€˜b’: 2, β€˜c’: 3}

Answer: a

Explanation: The copy() method creates a shallow copy, so modifying new_dict does not affect my_dict.

Q25. What will be the output of the following Python code snippet?

my_dict = {'a': 1, 'b': 2, 'c': 3}
result = list(my_dict.keys())
print(result)

a) [β€˜a’, β€˜b’, β€˜c’]

b) [β€˜c’, β€˜b’, β€˜a’]

c) [β€˜a’, 1, β€˜b’, 2, β€˜c’, 3]

d) Error: β€˜dict_keys’ object is not subscriptable

Answer: a

Explanation: list(my_dict.keys()) converts the keys of the dictionary to a list.

Q26. What will be the output of the following Python code snippet?

def deep_update_dict(d1, d2):
 for k, v in d2.items():
 if k in d1 and isinstance(d1[k], dict) and isinstance(v, dict):
 deep_update_dict(d1[k], v)
 else:
 d1[k] = v

my_dict1 = {'a': 1, 'b': {'c': 2}}
my_dict2 = {'b': {'d': 3}}
deep_update_dict(my_dict1, my_dict2)
print(my_dict1)

a) {β€˜a’: 1, β€˜b’: {β€˜c’: 2, β€˜d’: 3}}

b) {β€˜a’: 1, β€˜b’: {β€˜d’: 3}}

c) {β€˜a’: 1, β€˜b’: {β€˜c’: 2}}

d) {β€˜b’: {β€˜c’: 2, β€˜d’: 3}}

Answer: a

Explanation: The deep_update_dict function recursively updates my_dict1 with key-value pairs from my_dict2. Since both β€˜b’ in my_dict1 and my_dict2 are dictionaries, it recursively updates β€˜b’ in my_dict1 with the key-value pair β€˜d’: 3 from my_dict2.

Q27. What will be the output of the following Python code snippet?

def dict_merger(dict1, dict2):
 """
 Merges two dictionaries into a single dictionary.
 
 Arguments:
 dict1 -- First dictionary
 dict2 -- Second dictionary
 
 Returns:
 dict -- Merged dictionary
 """
 merged_dict = dict1.copy()
 merged_dict.update(dict2)
 return merged_dict

# Example usage:
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
result = dict_merger(dict1, dict2)
print(result)

a) {β€˜a’: 1, β€˜b’: 3, β€˜c’: 4}

b) {β€˜a’: 1, β€˜b’: 2, β€˜c’: 4}

c) {β€˜a’: 1, β€˜b’: 2}

d) {β€˜b’: 3, β€˜c’: 4}

Answer: a

Explanation: The dict_merger function merges dict2 into dict1 using the update method, overwriting values for keys that exist in both dictionaries.

Q28. What will be the output of the following Python code?

def dict_value_sum(d):
 """
 Sums all the values in a dictionary.
 
 Arguments:
 d -- Dictionary
 
 Returns:
 int -- Sum of all values
 """
 return sum(d.values())

# Example usage:
my_dict = {'a': 1, 'b': 2, 'c': 3}
result = dict_value_sum(my_dict)
print(result)

a) 5

b) 6

c) 7

d) 8

Answer: c

Explanation: The dict_value_sum function calculates the sum of all the values in the dictionary my_dict, which is 1 + 2 + 3 = 6.

Q29. What does the following Python code do?

my_dict = {'a': 1, 'b': 2, 'c': 3}
my_dict['d'] = 4
print(my_dict)

a) Adds a new key β€˜d’ with value 4 to the dictionary my_dict

b) Adds a new key β€˜4’ with value β€˜d’ to the dictionary my_dict

c) Removes the key β€˜d’ from the dictionary my_dict

d) Updates the value of key β€˜d’ to 4 in the dictionary my_dict

Answer: a

Explanation: The code adds a new key β€˜d’ with value 4 to the dictionary my_dict.

Q30. What type of error will the following code produce?

my_dict = {'a': 1, 'b': 2, 'c': 3}
del my_dict['d']
print(my_dict)

a) SyntaxError

b) KeyError

c) IndexError

d) No error

Answer: b

Explanation: The code will raise a KeyError because β€˜d’ does not exist as a key in the dictionary my_dict.

Q31. What type of error will the following code produce?

my_dict = {'a': 1, 'b': 2, 'c': 3}
keys = my_dict.keys()
print(keys[0])

a) SyntaxError

b) KeyError

c) TypeError

d) IndexError

Answer: c

Explanation: The code will raise a TypeError because the keys() method returns a view object, not a list, so it does not support indexing.

Q32. Which of the following is NOT a valid way to create a Python dictionary?

a) my_dict = {'a': 1, 'b': 2, 'c': 3}

b) my_dict = dict(a=1, b=2, c=3)

c) my_dict = dict([('a', 1), ('b', 2), ('c', 3)])

d) my_dict = dict(a=1, b=2, c=3, 'd'=4)

Answer: d

Explanation: The syntax dict(a=1, b=2, c=3, 'd'=4) is not valid because dictionary keys cannot be specified using both the keyword argument syntax (key=value) and the literal syntax ('key': value) in the same expression.

Q33. Which of the following is true about dictionaries in Python 3.7+?

a) Dictionaries are ordered by default, maintaining the order of elements as they are added.

b) Dictionaries are unordered by default, with no guarantee of element order.

c) Dictionaries are ordered only if explicitly specified with the OrderedDict class.

d) Dictionaries are ordered, but the order is randomized for better performance.

Answer: a

Explanation: Since Python 3.7, dictionaries are ordered by default, meaning they preserve the order of elements as they are added. This behavior was guaranteed starting from Python 3.7+.

Q34. What is the time complexity for accessing an item in a Python dictionary by its key?

a) O(1)

b) O(log n)

c) O(n)

d) O(n log n)

Answer: a

Explanation: Accessing an item in a Python dictionary by its key has an average time complexity of O(1). This is because dictionaries use a hash table implementation, providing constant-time lookup.

Congratulations on completing the Python Dictionary Manipulation MCQs! Dictionaries are essential data structures in Python, offering efficient ways to store and retrieve key-value pairs. By mastering dictionary manipulation techniques, you gain the ability to work with complex data structures and perform tasks such as data retrieval, modification, and validation. Keep practicing and experimenting with Python’s dictionary functionalities to become proficient in handling dictionaries within your programs. If you have any questions or want to delve deeper into any topic, don’t hesitate to continue your learning journey. Happy coding!

You can also enroll in our free Python Course Today!

Read our more articles related to MCQs in Python:

My name is Ayushi Trivedi. I am a B. Tech graduate. I have 3 years of experience working as an educator and content editor. I have worked with various python libraries, like numpy, pandas, seaborn, matplotlib, scikit, imblearn, linear regression and many more. I am also an author. My first book named #turning25 has been published and is available on amazon and flipkart. Here, I am technical content editor at Analytics Vidhya. I feel proud and happy to be AVian. I have a great team to work with. I love building the bridge between the technology and the learner.

Login to continue reading and enjoy expert-curated content.

Free Courses

Generative AI - A Way of Life

Explore Generative AI for beginners: create text and images, use top AI tools, learn practical skills, and ethics.

Getting Started with Large Language Models

Master Large Language Models (LLMs) with this course, offering clear guidance in NLP and model training made simple.

Building LLM Applications using Prompt Engineering

This free course guides you on building LLM apps, mastering prompt engineering, and developing chatbots with enterprise data.

Improving Real World RAG Systems: Key Challenges & Practical Solutions

Explore practical solutions, advanced retrieval strategies, and agentic RAG systems to improve context, relevance, and accuracy in AI-driven applications.

Microsoft Excel: Formulas & Functions

Master MS Excel for data analysis with key formulas, functions, and LookUp tools in this comprehensive course.

Responses From Readers

Flagship Programs

GenAI Pinnacle Program| GenAI Pinnacle Plus Program| AI/ML BlackBelt Program| Agentic AI Pioneer Program

Free Courses

Generative AI| DeepSeek| OpenAI Agent SDK| LLM Applications using Prompt Engineering| DeepSeek from Scratch| Stability.AI| SSM & MAMBA| RAG Systems using LlamaIndex| Building LLMs for Code| Python| Microsoft Excel| Machine Learning| Deep Learning| Mastering Multimodal RAG| Introduction to Transformer Model| Bagging & Boosting| Loan Prediction| Time Series Forecasting| Tableau| Business Analytics| Vibe Coding in Windsurf| Model Deployment using FastAPI| Building Data Analyst AI Agent| Getting started with OpenAI o3-mini| Introduction to Transformers and Attention Mechanisms

Popular Categories

AI Agents| Generative AI| Prompt Engineering| Generative AI Application| News| Technical Guides| AI Tools| Interview Preparation| Research Papers| Success Stories| Quiz| Use Cases| Listicles

Generative AI Tools and Techniques

GANs| VAEs| Transformers| StyleGAN| Pix2Pix| Autoencoders| GPT| BERT| Word2Vec| LSTM| Attention Mechanisms| Diffusion Models| LLMs| SLMs| Encoder Decoder Models| Prompt Engineering| LangChain| LlamaIndex| RAG| Fine-tuning| LangChain AI Agent| Multimodal Models| RNNs| DCGAN| ProGAN| Text-to-Image Models| DDPM| Document Question Answering| Imagen| T5 (Text-to-Text Transfer Transformer)| Seq2seq Models| WaveNet| Attention Is All You Need (Transformer Architecture) | WindSurf| Cursor

Popular GenAI Models

Llama 4| Llama 3.1| GPT 4.5| GPT 4.1| GPT 4o| o3-mini| Sora| DeepSeek R1| DeepSeek V3| Janus Pro| Veo 2| Gemini 2.5 Pro| Gemini 2.0| Gemma 3| Claude Sonnet 3.7| Claude 3.5 Sonnet| Phi 4| Phi 3.5| Mistral Small 3.1| Mistral NeMo| Mistral-7b| Bedrock| Vertex AI| Qwen QwQ 32B| Qwen 2| Qwen 2.5 VL| Qwen Chat| Grok 3

AI Development Frameworks

n8n| LangChain| Agent SDK| A2A by Google| SmolAgents| LangGraph| CrewAI| Agno| LangFlow| AutoGen| LlamaIndex| Swarm| AutoGPT

Data Science Tools and Techniques

Python| R| SQL| Jupyter Notebooks| TensorFlow| Scikit-learn| PyTorch| Tableau| Apache Spark| Matplotlib| Seaborn| Pandas| Hadoop| Docker| Git| Keras| Apache Kafka| AWS| NLP| Random Forest| Computer Vision| Data Visualization| Data Exploration| Big Data| Common Machine Learning Algorithms| Machine Learning| Google Data Science Agent
πŸ‘ Av Logo White

Continue your learning for FREE

Forgot your password?
πŸ‘ Av Logo White

Enter OTP sent to

Edit

Wrong OTP.

Enter the OTP

Resend OTP

Resend OTP in 45s

πŸ‘ Popup Banner
πŸ‘ AI Popup Banner