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
How to Add Values to Dictionary in Python
The task of adding values to a dictionary in Python involves inserting new key-value pairs or modifying existing ones. A dictionary stores data in key-value pairs, where each key must be unique. Adding values allows us to expand or update the dictionary's contents, enabling dynamic manipulation of d
3 min read
How to Update a Dictionary in Python
This article explores updating dictionaries in Python, where keys of any type map to values, focusing on various methods to modify key-value pairs in this versatile data structure. Update a Dictionary in PythonBelow, are the approaches to Update a Dictionary in Python: Using with Direct assignmentUs
3 min read
How to Print a Dictionary in Python
Python Dictionaries are the form of data structures that allow us to store and retrieve the key-value pairs properly. While working with dictionaries, it is important to print the contents of the dictionary for analysis or debugging. Example: Using print Function [GFGTABS] Python # input dictionary
3 min read
How to format a string using a dictionary in Python
In Python, we can use a dictionary to format strings dynamically by replacing placeholders with corresponding values from the dictionary. For example, consider the string "Hello, my name is {name} and I am {age} years old." and the dictionary {'name': 'Alice', 'age': 25}. The task is to format this
3 min read
Add a key value pair to Dictionary in Python
The task of adding a key-value pair to a dictionary in Python involves inserting new pairs or updating existing ones. This operation allows us to expand the dictionary by adding new entries or modify the value of an existing key. For example, starting with dictionary d = {'key1': 'geeks', 'key2': 'f
3 min read
Python Add to Dictionary Without Overwriting
Dictionaries in Python are versatile data structures that allow you to store and manage key-value pairs. One common challenge when working with dictionaries is how to add new key-value pairs without overwriting existing ones. In this article, we'll explore five simple and commonly used methods to ac
2 min read
Python - Add Items to Dictionary
We are given a dictionary and our task is to add a new key-value pair to it. For example, if we have the dictionary d = {"a": 1, "b": 2} and we add the key "c" with the value 3, the output will be {'a': 1, 'b': 2, 'c': 3}. This can be done using different methods like direct assignment, update(), or
3 min read
Python - Add Values to Dictionary of List
A dictionary of lists allows storing grouped values under specific keys. For example, in a = {'x': [10, 20]}, the key 'x' maps to the list [10, 20]. To add values like 30 to this list, we use efficient methods to update the dictionary dynamically. Letâs look at some commonly used methods to efficien
3 min read
How to Print Dictionary Keys in Python
We are given a dictionary and our task is to print its keys, this can be helpful when we want to access or display only the key part of each key-value pair. For example, if we have a dictionary like this: {'gfg': 1, 'is': 2, 'best': 3} then the output will be ['gfg', 'is', 'best']. Below, are the me
2 min read
Add Same Key in Python Dictionary
The task of adding the same key in a Python dictionary involves updating the value of an existing key rather than inserting a new key-value pair. Since dictionaries in Python do not allow duplicate keys, adding the same key results in updating the value of that key. For example, consider a dictionar
3 min read