Home > Software engineering >  how to filter the values of dictionaries of a list based on the certain value and arrange them in so
how to filter the values of dictionaries of a list based on the certain value and arrange them in so

Time:03-15

I have a list of dictionaries, it has different combinations of keys and values.

list_ = [{'r':'640x360','b':500},{'r':'1280x720','b':3000}, {'r':'1920x1080','b':4000},{'r':'1920x1080','b':5000}, {'r':'1280x720','b':3100}, {'b':'1280x720','t':3300}]

I want this dictionary to be sorted first, and then based on the value of 'b' it has to be modified. Suppose for the resolution value 'r' is '1280x720' and it has different bitrates in 'b' in different dictionaries.

Let's take example of '1280x720' case. for '1280x720' I want minimum bitrate would be 2000. If the value 'b' is lesser than the 2000, it has to take 2000 as 'b'.

If the 2 dictionaries same resolution and have -300 difference in bitrate 'b' then it has to keep the dict with higher value and pop out the other.

And if the value 'b' is more than the minimum we have to keep that dictionary too.

Entries of '1280x720' in input

[{'r':'1280x720','b':3000},{'r':'1280x720','b':3100}, {'b':'1280x720','t':3300},{'r':'1280x720','b':1300}, {'r':'1280x720','b':2500}]

Entries of '1280x720' in the output I am expecting.

[{'r':'1280x720','b':2000},{'r':'1280x720','b':2500},{'r':'1280x720','b':3300}]

I have tried sorting them with below piece of code but unable to continue the rest.

new_rep = [dict(t) for t in set(tuple(d.items()) for d in list_)]

I got the list of sorted dicts.

Any help would be appreciated.

CodePudding user response:

This looks to work :

data = [{'r':'1280x720','b':3000},{'r':'1280x720','b':3100}, {'r':'1280x720','b':3300},{'r':'1280x720','b':1300}]
sorted_data = sorted(data, key=lambda d: -d['b'])

print(sorted_data)

result = []
for item in sorted_data:
    if item['b'] < 2000:
        item['b'] = 2000
    new_res = True
    for res_item in result:
        if (res_item['b'] > item['b']  and res_item['b'] - item['b'] <= 300) or (res_item['b'] < item['b']  and item['b']  - res_item['b'] <= 300):
            new_res = False
    if new_res:
        result.append(item)

result = sorted(result, key=lambda d: d['b'])
print(result)

output :

[{'r': '1280x720', 'b': 2000}, {'r': '1280x720', 'b': 2500}, {'r': '1280x720', 'b': 3300}]
  • Related