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:
Convert Lists to Nested Dictionary - Python
Next article icon

Ways to create a dictionary of Lists – Python

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

A dictionary of lists is a type of dictionary where each value is a list. These dictionaries are commonly used when we need to associate multiple values with a single key.

Initialize a Dictionary of Lists

This method involves manually defining a dictionary where each key is explicitly assigned a list of values.

Example:

Python
# Creating an empty dictionary d = {}  # Adding list as value d["1"] = [1, 2] d["2"] = ["Geeks", "For", "Geeks"]   print(d) 

Output
{'1': [1, 2], '2': ['Geeks', 'For', 'Geeks']} 

Explanation:

  • A dictionary where each key is paired with a list (e.g., [1, 2]).
  • This is the most straightforward way to define a dictionary of lists but requires hardcoding all the keys and values.

Let’s look at other methods of creating a dictionary of lists:

Table of Content

  • Using the zip() Function
  • Use defaultdict from collections
  • Using setdefault()
  • Using Dictionary Comprehension

Using the zip() Function

zip() function can combine two lists (keys and lists of values) into a dictionary of lists. This method is efficient when the data is already structured as two separate lists.

Example:

Python
k = ["Fruits", "Vegetables", "Drinks"] val = [["Apple", "Banana"], ["Carrot", "Spinach"], ["Water", "Juice"]]  # Create a dictionary of lists using zip d = dict(zip(k, val))  print(d) 

Output
{'Fruits': ['Apple', 'Banana'], 'Vegetables': ['Carrot', 'Spinach'], 'Drinks': ['Water', 'Juice']} 

Explanation:

  • zip(keys, values) combines the keys and values lists into pairs (tuples).
  • dict() converts the resulting pairs into a dictionary.

Use defaultdict from collections

defaultdict automatically creates a default value for keys that don’t exist, making it ideal for building a dictionary of lists dynamically.

Example:

Python
from collections import defaultdict  # Initialize a defaultdict with list as the default type d = defaultdict(list)  # Add values to the dictionary d[1].append("Apple") d[2].append("Banana") d[3].append("Carrot")  print(d) 

Output
defaultdict(<class 'list'>, {1: ['Apple'], 2: ['Banana'], 3: ['Carrot']}) 

Explanation:

  • defaultdict(list) automatically assigns an empty list as the default value for keys that don’t exist.
  • append() adds items to the lists associated with the keys. No need to check if the key exists beforehand.

Using setdefault()

setdefault() method simplifies handling missing keys by initializing a default list if the key doesn’t exist.

Example:

Python
li = [("Fruits", "Apple"), ("Fruits", "Banana"), ("Vegetables", "Carrot")]  # Initialize an empty dictionary d = {}  # Use setdefault to populate the dictionary for k, item in li:     d.setdefault(k, []).append(item)  print(d) 

Output
{'Fruits': ['Apple', 'Banana'], 'Vegetables': ['Carrot']} 

Explanation:

  • setdefault(category, []) checks if the key exists; if not, it creates the key with an empty list as its value.

Using Dictionary Comprehension

Dictionary comprehension is a concise way to create a dictionary of lists from structured data.

Example:

Python
li = [("Fruits", "Apple"), ("Fruits", "Banana"), ("Vegetables", "Carrot")]  # Create dictionary of lists using comprehension d = {k: [i for _, i in filter(lambda x: x[0] == k, li)] for k in set(k for k, _ in li)}  print(d) 

Output
{'Fruits': ['Apple', 'Banana'], 'Vegetables': ['Carrot']} 

Explanation:

  • filter(lambda x: x[0] == k, li) filters items matching the current key.
  • Comprehension iterates over unique keys and assigns a list of all matching items as the value.


Next Article
Convert Lists to Nested Dictionary - Python

S

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

Similar Reads

  • 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
  • Convert a list of Tuples into Dictionary - Python
    Converting a list of tuples into a dictionary involves transforming each tuple, where the first element serves as the key and the second as the corresponding value. For example, given a list of tuples a = [("a", 1), ("b", 2), ("c", 3)], we need to convert it into a dictionary. Since each key-value p
    3 min read
  • Create a List of Tuples in Python
    The task of creating a list of tuples in Python involves combining or transforming multiple data elements into a sequence of tuples within a list. Tuples are immutable, making them useful when storing fixed pairs or groups of values, while lists offer flexibility for dynamic collections. For example
    3 min read
  • Convert Two Lists into a Dictionary - Python
    We are given two lists, we need to convert both of the list into dictionary. For example we are given two lists a = ["name", "age", "city"], b = ["Geeks", 30,"Delhi"], we need to convert these two list into a form of dictionary so that the output should be like {'name': 'Geeks', 'age': 30, 'city': '
    3 min read
  • Convert Lists to Nested Dictionary - Python
    The task of converting lists to a nested dictionary in Python involves mapping elements from multiple lists into key-value pairs, where each key is associated with a nested dictionary. For example, given the lists a = ["gfg", "is", "best"], b = ["ratings", "price", "score"], and c = [5, 6, 7], the g
    3 min read
  • How to Create a List of N-Lists in Python
    In Python, we can have a list of many different kinds, including strings, numbers, and more. Python also allows us to create a nested list, often known as a two-dimensional list, which is a list within a list. Here we will cover different approaches to creating a list of n-lists in Python. The diffe
    3 min read
  • Python | Convert list of tuple into dictionary
    Given a list containing all the element and second list of tuple depicting the relation between indices, the task is to output a dictionary showing the relation of every element from the first list to every other element in the list. These type of problems are often encountered in Coding competition
    8 min read
  • How to use a List as a key of a Dictionary in Python 3?
    In Python, we use dictionaries to check if an item is present or not . Dictionaries use key:value pair to search if a key is present or not and if the key is present what is its value . We can use integer, string, tuples as dictionary keys but cannot use list as a key of it . The reason is explained
    3 min read
  • Add new keys to a dictionary in Python
    In this article, we will explore various methods to add new keys to a dictionary in Python. Let's explore them with examples: Using Assignment Operator (=)The simplest way to add a new key is by using assignment operator (=). [GFGTABS] Python d = {"a": 1, "b": 2} d["c"]
    2 min read
  • Python - Access Dictionary items
    A dictionary in Python is a useful way to store data in pairs, where each key is connected to a value. To access an item in the dictionary, refer to its key name inside square brackets. Example: [GFGTABS] Python a = {"Geeks": 3, "for": 2, "geeks": 1} #Access the value a
    3 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