How do you merge a list of dictionaries with duplicate values to create a nested dict?

How do you merge a list of dictionaries with duplicate values to create a nested dict?

python merge list of dictionaries with same keys
python merge list of dictionaries by key
merge multiple dictionaries python
python merge dictionaries with same values
python merge dictionaries with common keys
merge nested dictionaries python
python dictionary sum values with same key
write a python program to combine values in python list of dictionaries

I have a dictionary of the form:

[
    {
        "group_name": "CUSTOMER_RED",
        "interface": "ae4",
        "unit_name": 2520
    },
    {
        "group_name": "CUSTOMER_RED",
        "interface": "ae4",
        "unit_name": 4091
    },
    {
        "group_name": "CUSTOMER_BLUE",
        "interface": "ae4",
        "unit_name": 847
    },
    {
        "group_name": "CUSTOMER_BLUE",
        "interface": "ae4",
        "unit_name": 103
    }
}

How can I merge it to form a list like:

[
    {
        "group_name": "CUSTOMER_RED",
        "interface": "ae4",
        "unit_names": [2520, 4091]
    },
    {
        "group_name": "CUSTOMER_BLUE",
        "interface": "ae4",
        "unit_names": [847, 103]
    },
}

or if it is easier:

[
    {
        "group_name": "CUSTOMER_RED",
        "interfaces": ["ae4": "unit_names": [2520, 4091]]
    },
    {
        "group_name": "CUSTOMER_BLUE",
        "interface": ["ae4": "unit_names": [847, 103]]
    },
}

I tried this:

def merge_relevant_config(config):
    return_config = []
    for item in config:
        name = item['group_name']
        interface = item['interface']
        units = []
        for item in config:
            if item['group_name'] == name and item['interface'] == interface:
                units.append(item['unit_name'])
        return_config.append({
            'name': name,
            'interface': interface,
            'units': units
        })
    return return_config

However this returns duplciates:

[
    {
        "name": "CUSTOMER_RED",
        "interface": "ae4",
        "units": [
            2520,
            4091
        ]
    },
    {
        "name": "CUSTOMER_RED",
        "interface": "ae4",
        "units": [
            2520,
            4091
        ]
    },
    {
        "name": "CUSTOMER_BLUE",
        "interface": "ae4",
        "units": [
            847,
            103
        ]
    },
    {
        "name": "CUSTOMER_BLUE",
        "interface": "ae4",
        "units": [
            847,
            103
        ]
    }
]

This is one approach.

Ex:

data = [
    {
        "group_name": "CUSTOMER_RED",
        "interface": "ae4",
        "unit_name": 2520
    },
    {
        "group_name": "CUSTOMER_RED",
        "interface": "ae4",
        "unit_name": 4091
    },
    {
        "group_name": "CUSTOMER_BLUE",
        "interface": "ae4",
        "unit_name": 847
    },
    {
        "group_name": "CUSTOMER_BLUE",
        "interface": "ae4",
        "unit_name": 103
    }
]

result = {}
for i in data:
    if i['group_name'] not in result:
        #if group by `group_name` & `interface` use --> result[(i['group_name'], i['interface'])]
        result[i['group_name']] = {'group_name': i['group_name'], 'interface': i['interface'], "unit_names": [i['unit_name']]}
    else:
        result[i['group_name']]["unit_names"].append(i['unit_name'])

print(list(result.values()))

Output:

[
    {
        'group_name': 'CUSTOMER_RED',
        'interface': 'ae4',
        'unit_names': [2520, 4091]
    },
    {
        'group_name': 'CUSTOMER_BLUE',
        'interface': 'ae4',
        'unit_names': [847, 103]
    }
]

Python, Given two list of dictionaries, the task is to merge these two lists of dictionaries based on some value. Method #1: Using defaultdict and extend to merge two list of dictionaries based on school_id. filter_none. edit close based on some value . first_page Python | Convert nested dictionary into flattened dictionary. Next. This is the most Pythonic way to merge multiple dictionaries into a single one and it works for an arbitrary number of dictionaries. Method 2: Simple Nested Loop. Use a simple nested loop to add each (key, value) pair separately to a newly created dictionary: Create a new, empty dictionary. Go over each dictionary in the list of dictionaries.


The other answer does not take in to account multiple interfaces, this example does:

def merge_config(config):
    merged = []
    sets = {}
    for item in config:
        as_text = '{}-{}'.format(item['group_name'], item['interface'])
        if as_text in sets.keys():
            sets[as_text].append(item['unit_name'])
        else:
            sets[as_text] = [item['unit_name']]

    for k, v in sets.items():
        group_name, interface = k.split('-')
        merged.append(
            {
                'group_name': group_name,
                'interface': interface,
                'unit_names': v
            }
        )
   return merged

Python, By using the method update() in Python, one list can be merged into another. But in this, the second list is merged into the first list and no new list is created. It returns None. Example: Python code to merge dict using update() method This will replace the duplicate keys of the first dictionary. Example:. What if we want to keep all the values ? Merge two dictionaries and add values of common keys. Suppose we have two dictionaries with common key i.e. # Create first dictionary dict1 = { 'Ritika': 5, 'Sam': 7, 'John' : 10 } # Create second dictionary dict2 = {'Aadi': 8,'Sam': 20,'Mark' : 11 }


Here's one with some versatility using itertools.groupy and a custom function. You can define the key you want to group by, and without knowing the inner keys you can still fully merge the dictionaries:

from itertools import groupby

def merge_dicts(*dcts):
    # define a merge function
    merged = {}
    for dct in dcts:
        for k, v in dct.items():            
            if merged.setdefault(k, v) != v:
                if not isinstance(merged.get(k), list):
                    merged[k] = [merged.get(k)]
                merged.get(k).append(v)
    return merged

group_key = 'group_name'
result = [merge_dicts(*grouped) for key, grouped in groupby(l, lambda dct: dct.get(group_key))]

Output:

[
  {
    'group_name': 'CUSTOMER_RED',
    'interface': 'ae4',
    'unit_name': [2520, 4091]
  },
  {
    'group_name': 'CUSTOMER_BLUE',
    'interface': 'ae4',
    'unit_name': [847, 103]
  }
]

How to Merge two or more Dictionaries in Python ? – thispointer.com, In Python, the Dictionary class provides a function update() i.e. Therefore, a new dictionary is created that contains the data from both the dictionaries. Merge 3 dictionary and keep values of common keys in a list. finalDict� A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.


To completely combine all common keys, you can use recursion with itertools.groupby:

from itertools import groupby as gb
data = [{'group_name': 'CUSTOMER_RED', 'interface': 'ae4', 'unit_name': 2520}, {'group_name': 'CUSTOMER_RED', 'interface': 'ae4', 'unit_name': 4091}, {'group_name': 'CUSTOMER_BLUE', 'interface': 'ae4', 'unit_name': 847}, {'group_name': 'CUSTOMER_BLUE', 'interface': 'ae4', 'unit_name': 103}]
def group(d):
   _d = [(a, list(b)) for a, b in gb(sorted(d, key=lambda x:x[0]), key=lambda x:x[0])]
   return [b if not (j:=[l for i in k if (l:=i[1:])]) else {a:{b:group(j)}} for (a, b), k in _d]

print(group([list(i.items()) for i in data]))

Output:

[{'group_name': {'CUSTOMER_BLUE': [{'interface': {'ae4': [103, 847]}}]}}, {'group_name': {'CUSTOMER_RED': [{'interface': {'ae4': [2520, 4091]}}]}}]

Python Dictionary, List List Slicing List Comprehension Tuple Set Dictionary Nested Dictionary Dict You can create a dictionary by placing a comma-separated list of key: value pairs to combine separate lists of keys and values obtained dynamically at runtime. values of different datatypes D = {'a':[1,2,3], 'b':{1,2,3}} # duplicate values D� Given a dictionary, the task is to find keys with duplicate values. Let’s discuss a few methods for the same. Method #1: Using Naive approach


How to Remove Duplicate Dictionaries in a List, Create a function to remove duplicate dictionaries from a list. to sort and stringify each dictionary and the set data type to ensure unique values. data that include nested dictionaries with similar and dissimilar nested keys. Merge Two Nested Dictionaries Use the built-in update () method to merge the keys and values of one nested dictionary into another. Note that this method blindly overwrites values of the same key if there’s a clash.


python create nested dictionary Code Example, Get code examples like "python create nested dictionary" instantly dictionary into nested list of dictionary python � append a list as value to� Now we want all the Values from above dictionary in a list i.e. [2, 43, 2, 23, 56, 23] Let’s see how to do that, Create a list of all values in dict using dict.values() In python, dictionary class provides a member function i.e. dict.values() It returns a view object / iterator to the list of all values in dictionary.


Find all occurences of a key in nested python dictionaries and lists , def find(key, dictionary): for k, v in dictionary.iteritems(): if k == key: yield v elif get all contained keys of a nested iterable as a list (also for the values) as can be � The basic method that comes to mind while performing this operation is the naive method of iterating the list of dictionaries and manually removing the duplicate dictionary and append in new list. filter_none