Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
How to Print a Dictionary in Python
Next article icon

How to Add User Input To A Dictionary - Python

Last Updated : 25 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

Table of Content

  • Using a list of tuples
  • Using update()
  • Using setdefault()

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.


Next Article
How to Print a Dictionary in Python
author
adarshmaster
Improve
Article Tags :
  • Python
  • Python Programs
Practice Tags :
  • python

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 Add Floats to a List in Python
    Adding floats to a list in Python is simple and can be done in several ways. The easiest way to add a float to a list is by using the append() method. This method adds a single value to the end of the list. [GFGTABS] Python a = [1.2, 3.4, 5.6] #Add a float value (7.8) to the end of the list a.append
    2 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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences