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:
Filter List of Python Dictionaries by Key in Python
Next article icon

Combine keys in a list of dictionaries in Python

Last Updated : 22 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Sometimes, while working with Python dictionaries, we can have a problem in which we need to perform a merge of dictionaries in list with similar keys. This kind of problem can come in data optimization domains. Let’s discuss a way in which this task can be performed.

Input : test_list = [{‘a’: 6}, {‘b’: 2}, {‘a’: 9}, {‘b’: 7}] 
Output : [{‘b’: 2, ‘a’: 6}, {‘b’: 7, ‘a’: 9}] 

Input : test_list = [{‘a’: 8}, {‘a’: 2}, {‘a’: 3}] 
Output : [{‘a’: 8}, {‘a’: 2}, {‘a’: 3}]

Method : loop + ** operator The combination of above functions can be used to solve this problem. In this, we use brute force to construct a new dictionary and add keys only if that is not added in current. The task of merging dictionaries is by unpacking the initial dictionaries using “**” operator, and then packing again with dictionary with no repeated key and new one, using the usual dictionary initialization construct {}. 

Python3




# Python3 code to demonstrate working of
# Merge Similar Dictionaries in List
# Using loop + "**" operator
 
# initializing list
test_list = [{'gfg' : 1}, {'is' : 2}, {'best' : 3},
              {'gfg' : 5}, {'is' : 17}, {'best' : 14},
              {'gfg' : 7}, {'is' : 8}, {'best' : 10},]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Merge Similar Dictionaries in List
# Using loop + "**" operator
res = [{}]
for sub in test_list:
    if list(sub)[0] not in res[-1]:
        res[-1] = {**res[-1], **sub}
    else:
        res.append(sub)
 
# printing result
print("The merged dictionaries : " + str(res))
 
 
Output : 

The original list is : [{‘gfg’: 1}, {‘is’: 2}, {‘best’: 3}, {‘gfg’: 5}, {‘is’: 17}, {‘best’: 14}, {‘gfg’: 7}, {‘is’: 8}, {‘best’: 10}] The merged dictionaries : [{‘best’: 3, ‘is’: 2, ‘gfg’: 1}, {‘best’: 14, ‘is’: 17, ‘gfg’: 5}, {‘best’: 10, ‘is’: 8, ‘gfg’: 7}]

Time complexity: O(n^2).
Auxiliary space: O(n).



Next Article
Filter List of Python Dictionaries by Key in Python
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python dictionary-programs
Practice Tags :
  • python

Similar Reads

  • Python - Common keys in list and dictionary
    Given a dictionary and list, extract all the keys and list which are common. Input : test_dict = {"Gfg": 3, "is" : 5, "best" : 9, "for" : 0, "geeks" : 3}, test_list = ["Gfg", "best", "CS"] Output : ['Gfg', 'best'] Explanation : Gfg and best are present in both dictionary and List. Input : test_dict
    8 min read
  • Python - Add custom values key in List of dictionaries
    The task of adding custom values as keys in a list of dictionaries involves inserting a new key-value pair into each dictionary within the list. In Python, dictionaries are mutable, meaning the key-value pairs can be modified or added easily. When working with a list of dictionaries, the goal is to
    5 min read
  • Python - Convert List to List of dictionaries
    We are given a lists with key and value pair we need to convert the lists to List of dictionaries. For example we are given two list a=["name", "age", "city"] and b=[["Geeks", 25, "New York"], ["Geeks", 30, "Los Angeles"], ["Geeks", 22, "Chicago"]] we need to convert these keys and values list into
    4 min read
  • Dictionary keys as a list in Python
    In Python, we will encounter some situations where we need to extract the keys from a dictionary as a list. In this article, we will explore various easy and efficient methods to achieve this. Using list() The simplest and most efficient way to convert dictionary keys to lists is by using a built-in
    2 min read
  • Filter List of Python Dictionaries by Key in Python
    In Python, filtering a list of dictionaries based on a specific key is a common task when working with structured data. In this article, we’ll explore different ways to filter a list of dictionaries by key from the most efficient to the least. Using List Comprehension List comprehension is a concise
    3 min read
  • Python - Convert List of Dictionaries to List of Lists
    We are given list of dictionaries we need to convert it to list of lists. For example we are given a list of dictionaries a = [{'name': 'Geeks', 'age': 25}, {'name': 'Geeks', 'age': 30}] we need to convert it in list of list so that the output becomes[['Geeks',25],['Geeks;'30]]. Using List Comprehen
    3 min read
  • Iterating List of Python Dictionaries
    Iteration of the list of dictionaries is a very common practice that every developer performs while encountering with dictionary data. In this article, we will explore how to iterate through a list of dictionaries. Iterating List Of Dictionaries in PythonBelow are some of the ways by which we can it
    3 min read
  • Get all Unique Keys from a List of Dictionaries - Python
    Our task is to get all unique keys from a list of dictionaries and we are given a list where each element is a dictionary, we need to extract and return a list of keys that appear across all dictionaries. The result should contain each key only once regardless of how many times it appears. For examp
    3 min read
  • Python - Compare Dictionaries on certain Keys
    Sometimes, while working with Python dictionaries, we can have a problem in which we need to compare dictionaries for equality on bases in selected keys. This kind of problem is common and has application in many domains. Lets discuss certain ways in which this task can be performed. Method #1 : Usi
    5 min read
  • Python - All combination Dictionary List
    Given 2 lists, form all possible combination of dictionaries that can be formed by taking keys from list1 and values from list2. Input : test_list1 = ["Gfg", "is", "Best"], test_list2 = [4] Output : [{'Gfg': 4, 'is': 4, 'Best': 4}]Explanation : All combinations dictionary list extracted. Input : tes
    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