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:
Python Print Dictionary Keys and Values
Next article icon

Python – Key Value list pairings in Dictionary

Last Updated : 01 Jun, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Sometimes, while working with Python dictionaries, we can have problems in which we need to pair all the keys with all values to form a dictionary with all possible pairings. This can have application in many domains including day-day programming. Lets discuss certain ways in which this task can be performed.

Method #1: Using list comprehension This task can be performed using this method. In this we manually extract each key and then iterate with all the values of them to form new dictionary list. This has drawbacks of only available for certain keys. 

Python3




# Python3 code to demonstrate working of
# Key Value list pairings in Dictionary
# Using list comprehension
 
# initializing dictionary
test_dict = {'gfg' : [7, 8],
             'best' : [10, 11, 7]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Key Value list pairings in Dictionary
# Using list comprehension
res = [{'gfg': i, 'best': j} for i in test_dict['gfg']
                           for j in test_dict['best']]
 
# printing result
print("All key value paired List : " + str(res))
 
 
Output : 

The original dictionary is : {‘gfg’: [7, 8], ‘best’: [10, 11, 7]} All key value paired List : [{‘gfg’: 7, ‘best’: 10}, {‘gfg’: 7, ‘best’: 11}, {‘gfg’: 7, ‘best’: 7}, {‘gfg’: 8, ‘best’: 10}, {‘gfg’: 8, ‘best’: 11}, {‘gfg’: 8, ‘best’: 7}]

The time complexity of the given code is O(N^2), where N is the size of the largest list in the dictionary.

The auxiliary space complexity of the given code is also O(N^2), as the result list ‘res’ contains N^2 key-value pairs, where N is the size of the largest list in the dictionary.

Method #2: Using dict() + zip() + product() The combination of above methods can also be used to perform this task. In this, the formation of combinations is done using product(), and linking of values is done using zip(). 

Python3




# Python3 code to demonstrate working of
# Key Value list pairings in Dictionary
# Using dict() + zip() + product()
from itertools import product
 
# initializing dictionary
test_dict = {'gfg' : [7, 8],
             'best' : [10, 11, 7]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Key Value list pairings in Dictionary
# Using dict() + zip() + product()
res = [dict(zip(test_dict, sub)) for sub in product(*test_dict.values())]
 
# printing result
print("All key value paired List : " + str(res))
 
 
Output : 

The original dictionary is : {‘gfg’: [7, 8], ‘best’: [10, 11, 7]} All key value paired List : [{‘gfg’: 7, ‘best’: 10}, {‘gfg’: 7, ‘best’: 11}, {‘gfg’: 7, ‘best’: 7}, {‘gfg’: 8, ‘best’: 10}, {‘gfg’: 8, ‘best’: 11}, {‘gfg’: 8, ‘best’: 7}]

Time Complexity: O(n*n), where n is the length of the list test_dict
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list

Method 3: Using a recursive approach 

Step-by-step approach:

  1. Define a function called key_value_combinations that takes two arguments: keys and values. The keys argument is a list of keys, and the values argument is a list of lists, where each inner list represents the possible values for a key.
  2. In the function, create an empty list called combinations.
  3. Define a recursive function called generate_combinations that takes two arguments: current_combination and remaining_values. The current_combination argument is a dictionary that represents the key-value pairs generated so far, and the remaining_values argument is a list of lists, where each inner list represents the possible values for a key that has not been assigned a value yet.
  4. In the generate_combinations function, if the remaining_values list is empty, append the current_combination dictionary to the combinations list and return.
  5. Otherwise, pop the first list from the remaining_values list, and iterate over its elements. For each element, create a new dictionary by adding a key-value pair to the current_combination dictionary, where the key is the first key from the keys list, and the value is the current element from the popped list. Call the generate_combinations function recursively with the updated current_combination dictionary and the remaining values in the remaining_values list.
  6. Call the generate_combinations function with an empty dictionary as the current_combination argument and the values list as the remaining_values argument.
  7. Return the combinations list.

Below is the implementation of the above approach:

Python3




def key_value_combinations(keys, values):
    def generate_combinations(current_combination, remaining_values):
        if not remaining_values:
            combinations.append(current_combination)
            return
        values_list = remaining_values[0]
        remaining_values = remaining_values[1:]
        for value in values_list:
            new_combination = current_combination.copy()
            new_combination[keys[0]] = value
            generate_combinations(new_combination, remaining_values)
    combinations = []
    generate_combinations({}, values)
    return combinations
test_dict = {'gfg' : [7, 8], 'best' : [10, 11, 7]}
combinations = key_value_combinations(list(test_dict.keys()), list(test_dict.values()))
print("All key value paired List : " + str(combinations))
 
 
Output
All key value paired List : [{'gfg': 10}, {'gfg': 11}, {'gfg': 7}, {'gfg': 10}, {'gfg': 11}, {'gfg': 7}]

Time complexity: O(n^m), where n is the maximum length of any value list, and m is the number of keys. 
Auxiliary space: O(n^m), as we need to store all possible combinations.

Method 4: Using itertools.product() with dictionary items()

Use the itertools.product() function along with the dictionary items() method to generate all possible combinations of key-value pairs.

Step-by-step approach:

  • Get the items in the dictionary using the items() method and store them in a list.
  • Use itertools.product() function to generate all possible combinations of values.
  • Combine each combination with the corresponding keys using the zip() function and store them in a list.

Below is the implementation of the above approach:

Python3




import itertools
 
def key_value_combinations(keys, values):
    items = list(zip(keys, values))
    value_combinations = itertools.product(*[item[1] for item in items])
    combinations = [{items[i][0]: combination[i] for i in range(len(items))} for combination in value_combinations]
    return combinations
 
test_dict = {'gfg' : [7, 8], 'best' : [10, 11, 7]}
combinations = key_value_combinations(list(test_dict.keys()), list(test_dict.values()))
print("All key value paired List : " + str(combinations))
 
 
Output
All key value paired List : [{'gfg': 7, 'best': 10}, {'gfg': 7, 'best': 11}, {'gfg': 7, 'best': 7}, {'gfg': 8, 'best': 10}, {'gfg': 8, 'best': 11}, {'gfg': 8, 'best': 7}]

Time complexity: O(n^m), where n is the maximum number of values for a key, and m is the number of keys.
Auxiliary space: O(n^m), to store all the combinations.

Method 5: Using nested for loops and a temporary dictionary

Step-by-step approach:

Define the dictionary test_dict with the given key-value pairs.
Print the original dictionary using print().
Initialize an empty list res to store the final result.
Use nested for loops to iterate over the values of the keys ‘gfg’ and ‘best’ in the dictionary test_dict.
For each pair of values, create a temporary dictionary temp_dict with the key-value pairs.
Append the temporary dictionary to the list res.
Print the final result using print().

Python3




# Python3 code to demonstrate working of
# Key Value list pairings in Dictionary
# Using nested for loops and a temporary dictionary
 
# initializing dictionary
test_dict = {'gfg' : [7, 8],
             'best' : [10, 11, 7]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Key Value list pairings in Dictionary
# Using nested for loops and a temporary dictionary
res = []
for i in test_dict['gfg']:
    for j in test_dict['best']:
        temp_dict = {}
        temp_dict['gfg'] = i
        temp_dict['best'] = j
        res.append(temp_dict)
 
# printing result
print("All key value paired List : " + str(res))
 
 
Output
The original dictionary is : {'gfg': [7, 8], 'best': [10, 11, 7]} All key value paired List : [{'gfg': 7, 'best': 10}, {'gfg': 7, 'best': 11}, {'gfg': 7, 'best': 7}, {'gfg': 8, 'best': 10}, {'gfg': 8, 'best': 11}, {'gfg': 8, 'best': 7}]

Time complexity: O(n^2), where n is the length of the longest list in the dictionary test_dict.
Auxiliary space: O(1), because the algorithm only uses a temporary dictionary and a list to store the final result, regardless of the size of the input.



Next Article
Python Print Dictionary Keys and Values
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python dictionary-programs
Practice Tags :
  • python

Similar Reads

  • Merge Key Value Lists into Dictionary Python
    Sometimes, while working with lists, we can come forward with a problem in which we need to perform the merge function in which we have the key list and need to create dictionary mapping keys with corresponding value in other list. Let's discuss certain ways in which this task can be performed. Merg
    8 min read
  • Python | List value merge in dictionary
    Sometimes, while working with dictionaries, we can have a problem in which we have many dictionaries and we are required to merge like keys. This problem seems common, but complex is if the values of keys are list and we need to add elements to list of like keys. Let's discuss way in which this prob
    5 min read
  • Python - Minimum value pairing for dictionary keys
    Given two lists, key and value, construct a dictionary, which chooses minimum values in case of similar key value pairing. Input : test_list1 = [4, 7, 4, 8], test_list2 = [5, 7, 2, 9] Output : {8: 9, 7: 7, 4: 2} Explanation : For 4, there are 2 options, 5 and 2, 2 being smallest is paired. Input : t
    7 min read
  • Python Print Dictionary Keys and Values
    When working with dictionaries, it's essential to be able to print their keys and values for better understanding and debugging. In this article, we'll explore different methods to Print Dictionary Keys and Values. Example: Using print() Method [GFGTABS] Python my_dict = {'a': 1, 'b'
    2 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 - Print dictionary of list values
    In this article, we will explore various ways on How to Print Dictionary in Python of list values. A dictionary of list values means a dictionary contains values as a list of dictionaries in Python. Example: {'key1': [{'key1': value,......,'key n': value}........{'key1': value,......,'key n': value}
    4 min read
  • Inverse Dictionary Values List - Python
    We are given a dictionary and the task is to create a new dictionary where each element of the value lists becomes a key and the original keys are grouped as lists of values for these new keys.For example: dict = {1: [2, 3], 2: [3], 3: [1]} then output will be {2: [1], 3: [1, 2], 1: [3]} Using defau
    2 min read
  • Python - Mapping Key Values to Dictionary
    We are given two list and we need to map key to values of another list so that it becomes dictionary. For example, we are given two list k = ['a', 'b', 'c'] and v = [1, 2, 3] we need to map the keys of list k to the values of list v so that the resultant output should be {'a': 1, 'b': 2, 'c': 3}. Us
    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
  • Get First N Key:Value Pairs in given Dictionary - Python
    We are given a dictionary and tasked with retrieving the first N key-value pairs. For example, if we have a dictionary like this: {'a': 1, 'b': 2, 'c': 3, 'd': 4} and we need the first 2 key-value pairs then the output will be: {'a': 1, 'b': 2}. Using itertools.islice()One of the most efficient ways
    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