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}]
CodePudding user response:
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()
]
CodePudding user response:
a = [{1: 2}, {1: 3}, {2: 5}, {2: 3}]
output = {}
for d in a:
k = list(d.keys())[0]
v = list(d.values())[0]
if k not in output.keys():
output[k] = v
else:
if output[k] < v:
output[k] = v
output = [{k:v} for k, v in output.items()]
print(output)
CodePudding user response:
from itertools import groupby
a = [{1: 2}, {1: 3}, {2: 5}, {2: 3}]
[{k, max(y[1] for y in g)} # build up the result by recreating the list of maps by taking the keys in the group and map them to the biggest value in the group
for k, g
in groupby((sorted( # group everything together, so that those touples with the same key (=index 0) are in the same group
((k, v) for m in a for k, v in m.items()) # transform the list of maps to a generator of tuples
, key=lambda x: x[0])), key=lambda x: x[0])]
So here I first transform the list of maps to a list of tuples (which makes much more sense, but that is just me), group them together by the key, and afterwards create new maps for each key, by taking the biggest value inside each group.
CodePudding user response:
Same logic as BrownieInMotion's approach, but with cleaner code using list comprehension for the result.
a = [{1: 2}, {1: 3}, {2: 5}, {2: 3}]
temp = {}
for item in a:
i, v = list(*item.items())
if i not in temp:
temp[i] = v
else:
temp[i] = max(v, temp[i])
print([{i: v} for i, v in temp.items()])
The unpacking usage list(*item.items())
restricts to dictionaries of single key. If you want to remove the restriction, you can go ahead and use list(item.items())[0]
.