Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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']}]

**

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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']}]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading