extract dictionaries from a list of dictionaries ( based on a condition from (key, value))

Viewed 28

I have a list of dictionaries such as:

data_list = [
    {"AB":1.23,  'height':60.0}, 
    {"AB":1.23,  'height':61.0}, 
    {"AB":1.23,  'height':60.0},
    {"AC":2.60,  'height':60.0},
    {"AC":2.60,  'height':62.0},
    {"AC":2.60,  'height':60.0},
]

Based on a different value of key "height" (the same height related dictionary is taken once),

I am looking for the output as follows:

data_list = [
   [{"AB":1.23,  'height':60.0}, 
    {"AB":1.23,  'height':61.0}, 
    {"AC":2.60,  'height':60.0},
    {"AC":2.60,  'height':62.0},]

Here is my try:

data_list = [
    {"AB":1.23,  'height':60.0}, 
    {"AB":1.23,  'height':61.0}, 
    {"AB":1.23,  'height':60.0},
    {"AC":2.60,  'height':60.0},
    {"AC":2.60,  'height':62.0},
    {"AC":2.60,  'height':60.0},
    ]

print(data_list)

new_data_list = []
for ii, idict in enumerate(data_list):
    for jj, jdict in enumerate(data_list):
        if jj >= ii+1: 
            if idict['height'] != jdict['height']:
                new_data_list.append(idict)
print(new_data_list)

How to obtain the required output?

1 Answers

You can solve this problem by creating a set of all the heights seen for each key, and only appending a dict to the result if the height has not been seen before. A defaultdict can simplify the code:

from collections import defaultdict

data_list = [
    {"AB":1.23,  'height':60.0}, 
    {"AB":1.23,  'height':61.0}, 
    {"AB":1.23,  'height':60.0},
    {"AC":2.60,  'height':60.0},
    {"AC":2.60,  'height':62.0},
    {"AC":2.60,  'height':60.0},
]

heights = defaultdict(set)
result = []
for d in data_list:
    k = [k for k in d.keys() if k != 'height'][0]
    if not d['height'] in heights[k]:
        heights[k].add(d['height'])
        result.append(d)

Output:

[
 {'AB': 1.23, 'height': 60.0},
 {'AB': 1.23, 'height': 61.0},
 {'AC': 2.6, 'height': 60.0},
 {'AC': 2.6, 'height': 62.0}
]
Related