How to Add User Input To A Dictionary - Python
Last Updated :
25 Jan, 2025
The task of adding user input to a dictionary in Python involves taking dynamic data from the user and storing it in a dictionary as key-value pairs. Since dictionaries preserve the order of insertion, we can easily add new entries based on user input.
For instance, if a user inputs "name" as the key and "John" as the value, we can directly assign "name": "John" to the dictionary, building it incrementally with each user input.
Using dictionary comprehension
Dictionary comprehension is a efficient way to populate a dictionary in a single step. By combining iteration and input collection in one line, this method minimizes the code required and makes it highly readable. It is ideal when we want to create a dictionary quickly from user input.
Python
n = int(input("Enter the number of entries: "))
d = {input("Enter key: "): input("Enter value: ") for _ in range(n)}
print(d)
Output
Enter the number of entries: 3
Enter key: Aditya
Enter value: 21
Enter key: Anish
Enter value: 32
Enter key: Arjun
Enter value: 10
{'Aditya': '21', 'Anish': '32', 'Arjun': '10'}
Explanation: This code takes an integer n
as the number of entries, collects n
key-value pairs and creates the dictionary d
.
Using a list of tuples
In this method, key-value pairs are first collected as a list of tuples and then converted into a dictionary using dict() . This approach provides a clean separation between data collection and dictionary creation and making it particularly useful when dealing with a large number of entries .
Python
n = int(input("Enter the number of entries: "))
entries = [(input("Enter key: "), input("Enter value: ")) for _ in range(n)]
d = dict(entries)
print(d)
Output
Enter the number of entries: 3
Enter key: Aditya
Enter value: 21
Enter key: Anish
Enter value: 32
Enter key: Arjun
Enter value: 10
{'Aditya': '21', 'Anish': '32', 'Arjun': '10'}
Explanation: This code takes an integer n as the number of entries, collects n key-value pairs as tuples then converts the list of tuples into a dictionary d using dict() .
Using update()
update() allows us to add or modify entries in an existing dictionary. By iterating through user input in a loop, this method incrementally updates the dictionary with new key-value pairs. It’s particularly helpful when working with dictionaries that are need to be modified.
Python
d = {} # initializes an empty dictionary
n = int(input("Enter the number of entries: "))
for _ in range(n):
key = input("Enter key: ")
value = input("Enter value: ")
d.update({key: value})
print(d)
Output
Enter the number of entries: 3
Enter key: Aditya
Enter value: 21
Enter key: Anish
Enter value: 32
Enter key: Arjun
Enter value: 10
{'Aditya': '21', 'Anish': '32', 'Arjun': '10'}
Explanation: This code takes an integer n as the number of entries then iterates n times to collect user inputs for keys and values, updating the dictionary d with each key-value pair using update().
Using setdefault()
setdefault() ensures that keys are added to a dictionary with default values if they don’t already exist. While this method is often used to handle default values, it can also be adapted for adding user input to a dictionary.
Python
d = {} # initializes an empty dictionary
n = int(input("Enter the number of entries: "))
for _ in range(n):
key = input("Enter key: ")
value = input("Enter value: ")
d.setdefault(key, value)
print(d)
Output
Enter the number of entries: 3
Enter key: Aditya
Enter value: 21
Enter key: Anish
Enter value: 32
Enter key: Arjun
Enter value: 10
{'Aditya': '21', 'Anish': '32', 'Arjun': '10'}
Explanation: This code takes an integer n as the number of entries then iterates n times to collect user inputs for keys and values, adding each key-value pair to the dictionary d using setdefault() ensuring that the key is only added if it doesn't already exist.
Similar Reads
Python Tutorial | Learn Python Programming Language
Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers
Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Non-linear Components
In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Python OOPs Concepts
Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced
Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions
Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs
Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Spring Boot Tutorial
Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML)
A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Steady State Response
In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read