Issue
There are some dictionary in list:
a = [{1: 2}, {1: 3}, {2: 5}, {2: 3}]
All of the keys and values of this dictionary are int type, some dicts have the same key, I want to remain those dictionaries who has the same key and the value is bigger than others, how can I do it? example: I want to obtain this list:
[{1: 3}, {2: 5}]
Solution
Assuming that each dictionary has only one key/value pair, here is a possible solution. Essentially, create a new dictionary to keep track of the maximum values for each key. Then, turn this into the final list.
def remove_duplicates(dicts):
merged = {}
for d in dicts:
key, value = list(d.items())[0]
if key not in merged:
merged[key] = value
else:
merged[key] = max(
merged[key], value
)
return [
{key: value}
for key, value in merged.items()
]
Answered By - BrownieInMotion
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.