[SOLVED] filter a list of dictionarys by key and values & add to the dictionary by specific key

Issue

I want to filter a list of dictionarys by key "IP" and value of that key.
This is my list for example.

**

a=[{'IP': '192.168.0.5', 'Temp1': ['58.0']}, 
   {'IP': '192.168.0.6', 'Temp1': ['59.1']}, 
   {'IP': '192.168.0.5', 'Temp2': ['59.1']}, 
   {'IP': '192.168.0.6', 'Temp2': ['60.7']}]

**

Is it possible to make it look like this?
I want to filter by "IP" so it looks like this:

**

filtered=[{'IP': '192.168.0.5', 'Temp1': ['58.0'],'Temp2': ['59.1']}, 
          {'IP': '192.168.0.6', 'Temp1': ['59.1'],'Temp2': ['60.7']}]

**

But I dont know how to exactly do it, can somebody please explain it to me?

Solution

This should do it:

        a=[{'IP': '192.168.0.5', 'Temp1': ['58.0']}, 
           {'IP': '192.168.0.6', 'Temp1': ['59.1']}, 
           {'IP': '192.168.0.5', 'Temp2': ['59.1']}, 
           {'IP': '192.168.0.6', 'Temp2': ['60.7']}]        
        filtered=[{'IP': '192.168.0.5', 'Temp1': ['58.0'],'Temp2': ['59.1']}, 
                  {'IP': '192.168.0.6', 'Temp1': ['59.1'],'Temp2': ['60.7']}]        
        
        import collections
        b = collections.defaultdict(dict)
        for d in a:
            for k, v in d.items():
                b[d['IP']][k] = v
        c = list(b.values())
        print(c)

Output is:

[{'IP': '192.168.0.5', 'Temp1': ['58.0'], 'Temp2': ['59.1']}, {'IP': '192.168.0.6', 'Temp1': ['59.1'], 'Temp2': ['60.7']}]

Answered By – constantstranger

Answer Checked By – Candace Johnson (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.