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

Group all values with the same identic key in list of tuples

I have a list of tuples with strings and dictionaries which looks like following:

# data type: List<Tuple<string, dict>>    
input_data_structure = [
('key1', {'a': 'b'}), 
('key2', {'w': 'x'}), 
('key1', {'c': 'd'}), 
('key2', {'y': 'z'})]

I want to group alle values with the same keys. So the result could look like this or similiar:

# data type: List<Tuple<string, List<dict>>>     
result_data_structure = [
('key1',  [{'a': 'b'}, {'c': 'd'}]), 
('key2',  [{'w': 'x'}, {'y': 'z'}])]

For me it is important to have a good data structure, where I can loop through the existing arrays of the keys to get the values like this:

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

for t in result:
     for val in t[1]:
         print(val)

Does someone has an idea how to process or transform the data? Thanks in advance!

>Solution :

You can use defaultdicts to achieve easily this.

from collections import defaultdict
d = defaultdict(list)

for key, value in input_data_structure:
    d[key].append(value)

d  # defaultdict(<class 'list'>, {'key1': [{'a': 'b'}, {'c': 'd'}], 'key2': [{'w': 'x'}, {'y': 'z'}]})

If you need your output to be a list of tuples key/value, then you can just execute this line.

list(d.items())  # [('key1', [{'a': 'b'}, {'c': 'd'}]), ('key2', [{'w': 'x'}, {'y': 'z'}])]
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