VOOZH about

URL: https://www.analyticsvidhya.com/blog/2022/07/top-interview-questions-on-dictionary-in-python/

⇱ Top Interview Questions on Dictionary in Python - Analytics Vidhya


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

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

Top Interview Questions on Dictionary in Python

saumyab271 Last Updated : 20 Jul, 2022
4 min read

This article was published as a part of the Data Science Blogathon.

Introduction

In python, Dictionary is an unordered collection of data values, i.e., key: value pair within the curly braces. The keys in the dictionary are unique (can’t be repeated), whereas values can be duplicated. Questions on Dictionary are often asked in interviews due to its massive use during projects.

Therefore, having a piece of good knowledge about dictionary for every Data Scientist aspirant.

In this article, some critical theoretical as well as practical questions will be discussed, which will help aspirants have a good understanding of the Dictionary.

πŸ‘ Dictionary in python

Interview Questions on Dictionary

Question 1: What is a dictionary?

Dictionary is a set of key: value pairs, with each pair being unique. The dictionary can be created by using empty braces {}. We can add a key: value pair to it.

eg-  dictionary1 = { β€˜a’: 1, β€˜b’: 2, β€˜c’: 3 }

Question 2: Are dictionaries case-sensitive?

Yes, dictionaries are case-sensitive, i.e., the same name of keys, but different cases are treated differently, i.e., β€˜apple’ and β€˜APPLE’ will be treated as separate keys.

Question 3: What are different ways of creating a Dictionary?

Three different ways of creating a Dictionary are:

1. Create an empty Dictionary

Dictionary1 = {}
print(Dictionary1)

Output:

{}
key1 = 'a'
value1 = 1
Dictionary1[key1] = value1
Output:
{'a': 1}
2. Create Dictionary using dict() method
Dictionary1 = dict({1: 'a', 2: 'b'})
print(Dictionary1)

Output:

{1: 'a', 2: 'b'}

3. Create Dictionary with each item as Pair

Dictionary1 = dict([(1,'a'), (2, 'b')])
print(Dictionary1)

Output:

{1: 'a', 2: 'b'}

4. Creating Dictionary directly

Dictionary1 = {1: 'a', 2: 'b'}

Output:

{1: 'a', 2: 'b'}

Question 4: What is a Nested Dictionary? How is it created?

A dictionary inside the dictionary is known as a β€œNested Dictionary”. For ex-

dictionary1 = {1: {'roll': '101', 'name': 'sam'},
                          2: {'roll': '102', 'name': 'ram'}}
print(dictionary1)

Output

{1: {'roll': '101', 'name': 'sam'}, 2: {'roll': '102', 'name': 'ram'}}

The elements of nested dictionary can be accessed using

print(dictionary[1]['roll'])

Output:

101

Question 5: How do you add an element in Dictionary?

Elements in a Dictionary can be added in multiple ways:

1. Adding one pair at a time

Dict1 ={}
Dict1[0] = 'a'
Dict1[1] = 'b'
print("Dictionary after adding 3 elements: ", Dict1)

Output:

{0: 'a', 1: 'b' }

2. Adding more than one value to a single key

Dict1['values'] = 4, 5, 6
print("Dictionary after adding multiple values to a key: ", Dict1)

Output:

{0: 'a', 1: 'b', 'values': (4, 5, 6) }

3. Adding nested key-value pair

Dict1['Nested'] = {1: 'Analytics', 2: 'Life'}

Output:

{0: 'a', 1: 'b', 'values': (4, 5, 6), 'Nested': {1: 'Analytics', 2: 'Life'} }

Question 6: Discuss different methods used with Dictionary.

Various methods used with Dictionary are:

1. clear()

It is used to delete all elements from a dictionary i.e., to create empty dictionary.

dict2 = {1: 'Analytics', 2: 'Vidhya'}
dict2.clear()
print(dict2)

Output:

{ }
2. get()

It is used to get the value of the specified key.

x = dict2.get(2)
print(x)

Output:

Vidhya

3. copy()

It is used to return copy of a dictionary

dict3 = dict2.copy()
print(dict3)

Output:

{1: 'Analytics', 2: 'Vidhya'}

4. items()

It is used to return a list tuples consisting of key-value pairs.

Dict1 = {1: 'Analytics', 2: 'Vidhya'}
print(Dict1.items())

Output:

dict_items([(1, 'Analytics'), (2, 'Vidhya')])

5. keys() and values()

Returns all keys and values within a dictionary respectively.

Dict1.key()
Dict1.values()

Output:

dict_keys([1, 2]) 
dict_values(['Analytics', 'Vidhya'])

6. update()

This method updated value of a key in dictionary

Dict1.update({2:"Blogathon"})
print(Dict1)

Output:

{1: 'Analytics', 2: 'Blogathon'}

Question 7: Create a dictionary from a given list. For instance-

Input : [1, β€˜a’, 2, β€˜b’, 3, β€˜c’] Output : {1: β€˜a’, 2: β€˜b’, 3: β€˜c’}

def Convert_list_dict(dict2):
x = iter(dict2)
res_dct1 = dict(zip(x, x))
return res_dct1
dict1 = [1, β€˜a’, 2, β€˜b’,3, β€˜c’]
print(Convert_list_dict(dict1))

Here, zip() function takes iterables (it can be more than two also) and combines them in a tuple.

Output:


{1: 'a', 2: 'b', 3: 'c'}

Question 8: Create a list of tuples from the dictionary

The list of tuples can be created in following way:

dict1 = { 1: 'a', 2: 'b', 3: 'c' }
lst1 = list(dict1.items())
print(lst1)

Output:

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

Question 9: Create a list from the dictionary.

Suppose the given dictionary is:

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

A list can be created using the below code:

x = list(dict1.keys())
y = list(dict1.values())
for i in y:
      x.append(i)
print(x)

Output:

[1, 2, 3, 'a', 'b', 'c']

Question 10: How can you delete key-value pair from Dictionary?

Key-value pair can be deleted by using β€˜del’ keyword as shown below:

del dict1[1]
print(dict1)

Output:

{2: 'b', 3: 'c' }

Question 11: Is the dictionary mutable?

The term β€˜Mutable’ means we can add, remove or update key-value pairs in a dictionary.

Yes, the dictionary is mutable. For instance,

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

Output:

{1: 'a', 2: 'h', 3: 'c', 4: 'd' }

Question 12: Given two lists, create a dictionary from them.

Input: [ 1, 2, 3, 4, 5], [β€˜a’, β€˜b’, β€˜c’, β€˜d’, β€˜e’]

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

Let’s define these two lists as list1 and list2 as follows:

list1 = [1, 2, 3, 4, 5]
list2 = ['a', 'b', 'c', 'd', 'e']
dict1 = {}
for i, j in zip(list1, list2):
 dict1[i] = j
print(dict1)

Output:

{1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}

Another way of achieving the same output:

dict1 = {i:h for i,j in zip(list1, list2)}
print(dict1)

Output:

{1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}

Question 13: Write a code to sort dictionaries using a key.

Input: {2: β€˜Apple’, 1:’Mango’, 3:’Orange’, 4:’Banana’}

Output: 1: Mango
2: Apple
3: Orange
4: Banana

Below is the code to sort dictionaries using the key:

dict1 = {2: 'Apple', 1:'Mango', 3:'Orange', 4:'Banana'}
print(sorted(dict1.keys()))
for key in sorted(dict1):
      print("Sorted dictionary using key:",(key, color_dict[key]))

Output:

[1, 2, 3, 4] 
1: Mango
2: Apple
3: Orange
4: Banana

Conclusion

In this blog, we studied some of the important and frequently asked interview questions on Dictionary. To sum up, the following are the major contributions of the article:

1. Basic concepts of the Dictionary have been discussed to make the reader familiar with it.

2. We learned how to perform various functions on Dictionary, such as adding key-value pairs and deleting key-value pairs.

3. We discussed various functions that can be used to work and play with Dictionary.

4. Further, we also discussed several programming questions on Dictionary that can be asked in interviews.

The media shown in this article is not owned by Analytics Vidhya and is used at the Author’s discretion.

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

nice piece of work. i really appreciate this. πŸ‘πŸ»

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