Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • 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:
Python - Add Dictionary Items
Next article icon

How to Create a Dictionary in Python

Last Updated : 08 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The task of creating a dictionary in Python involves storing key-value pairs in a structured and efficient manner, enabling quick lookups and modifications. A dictionary is an unordered, mutable data structure where each key must be unique and immutable, while values can be of any data type. For example, given two lists, keys = ['a', 'b', 'c'] and values = [1, 2, 3], the goal is to construct a dictionary like {'a': 1, 'b': 2, 'c': 3}, mapping each key to its corresponding value.

Using dict()

dict() constructor provides a simple and direct way to create dictionaries using keyword arguments. This method is useful for defining static key-value pairs in a clean and readable manner.

Python
d = dict(a=1, b=2, c=3) print(d) 

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

Explanation: dict() creates a dictionary by directly assigning key-value pairs as keyword arguments.

Table of Content

  • Using dict()
  • Using defaultdict
  • Using setdefault()
  • Using for loop

Using dictionary comprehension

Dictionary comprehension is a efficient way to create a dictionary from iterable sequences like lists or tuples. It allows mapping keys to values using a single line of code, making it highly readable and optimal for small to medium datasets.

Python
keys = ['a', 'b', 'c'] values = [1, 2, 3]  d = {k: v for k, v in zip(keys, values)} print(d) 

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

Explanation:{k: v for k, v in zip(keys, values)} iterates over key-value pairs generated by zip(), assigning each key to its respective value and constructing the dictionary d .

Using defaultdict

defaultdict is a powerful tool that automatically initializes missing keys with a default value. It is particularly useful for grouping multiple values under the same key without explicit key existence checks.

Python
from collections import defaultdict  a = [('a', 1), ('b', 2), ('a', 3), ('c', 4)] d = defaultdict(list) # Create a defaultdict with list as the default value type  for key, value in a:     d[key].append(value)  print(dict(d)) 

Output
{'a': [1, 3], 'b': [2], 'c': [4]} 

Explanation: for loop iterates through the list a , appending values directly, eliminating the need for key existence checks. Finally, the defaultdict is converted to a regular dictionary.

Using setdefault()

setdefault() method simplifies dictionary creation by initializing keys with a default value if they don’t already exist. This approach is helpful when handling dynamic data where keys may appear multiple times.

Python
a = [('a', 1), ('b', 2), ('a', 3), ('c', 4)] d = {}   for key, val in a:     d.setdefault(key, []).append(val)  print(d) 

Output
{'a': [1, 3], 'b': [2], 'c': [4]} 

Explanation:for loop extracts key and val from each tuple in a. setdefault(key, []) initializes an empty list for new keys, preventing errors and .append(val) then adds values, efficiently grouping multiple entries under the same key.

Using for loop

A traditional for loop can be used to create a dictionary by iterating over two lists or handling dynamic key-value assignments. This method is useful when additional operations or transformations are required before storing the data.

Python
keys = ['p', 'q', 'r'] values = [5, 10, 15]  d = {}  for i in range(len(keys)):     d[keys[i]] = values[i]  print(d) 

Output
{'p': 5, 'q': 10, 'r': 15} 

Explanation: for loop iterates through the keys list using an index-based loop. Each key from keys is mapped to its corresponding value from values using d[keys[i]] = values[i].


Next Article
Python - Add Dictionary Items

H

harshcooldude700
Improve
Article Tags :
  • Python
  • python-dict
  • Python dictionary-programs
Practice Tags :
  • python
  • python-dict

Similar Reads

    Dictionaries in Python
    Python dictionary is a data structure that stores the value in key: value pairs. Values in a dictionary can be of any data type and can be duplicated, whereas keys can't be repeated and must be immutable. Example: Here, The data is stored in key:value pairs in dictionaries, which makes it easier to
    5 min read
    How to Create a Dictionary in Python
    The task of creating a dictionary in Python involves storing key-value pairs in a structured and efficient manner, enabling quick lookups and modifications. A dictionary is an unordered, mutable data structure where each key must be unique and immutable, while values can be of any data type. For exa
    3 min read
    Python - Add Dictionary Items
    In Python, dictionaries are a built-in data structure that stores key-value pairs. Adding items to a dictionary is a common operation when you're working with dynamic data or building complex data structures. This article covers various methods for adding items to a dictionary in Python.Adding Items
    3 min read
    Python Add Dictionary Key
    In Python, dictionaries are unordered collections of key-value pairs. Each item in a dictionary is accessed by its unique key, which allows for efficient storage and retrieval of data. While dictionaries are commonly used with existing keys, adding a new key is an essential operation when working wi
    4 min read
    Python Access Dictionary
    In Python, dictionaries are powerful and flexible data structures used to store collections of data in key-value pairs. To get or "access" a value stored in a dictionary, we need to know the corresponding key. In this article, we will explore all the ways to access dictionary values, keys, and both
    4 min read
    Python Change Dictionary Item
    A common task when working with dictionaries is updating or changing the values associated with specific keys. This article will explore various ways to change dictionary items in Python.1. Changing a Dictionary Value Using KeyIn Python, dictionaries allow us to modify the value of an existing key.
    3 min read
    Python Remove Dictionary Item
    Sometimes, we may need to remove a specific item from a dictionary to update its structure. For example, consider the dictionary d = {'x': 100, 'y': 200, 'z': 300}. If we want to remove the item associated with the key 'y', several methods can help achieve this. Let’s explore these methods.Using pop
    2 min read
    Get length of dictionary in Python
    Python provides multiple methods to get the length, and we can apply these methods to both simple and nested dictionaries. Let’s explore the various methods.Using Len() FunctionTo calculate the length of a dictionary, we can use Python built-in len() method. It method returns the number of keys in d
    3 min read
    Python - Value length dictionary
    Sometimes, while working with a Python dictionary, we can have problems in which we need to map the value of the dictionary to its length. This kind of application can come in many domains including web development and day-day programming. Let us discuss certain ways in which this task can be perfor
    4 min read
    Python - Dictionary values String Length Summation
    Sometimes, while working with Python dictionaries we can have problem in which we need to perform the summation of all the string lengths which as present as dictionary values. This can have application in many domains such as web development and day-day programming. Lets discuss certain ways in whi
    4 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