Is there a better way to remove the duplicates and only keep the minimum value for each key in my dictionary without looping into the dictionary and without creating a new dictionary to append in it?
dic2 = {}
dic = {0: [4, 4, 4, 4, 5], 1: [3, 4, 4, 4]}
for key, value in dic.items():
min_value = min(value)
dic2[key] = min_value
print(dic2)
output
{0: 4, 1: 3}
使用字典理解:
dic2 = {k: min(v) for k, v in dic.items()}
I would be perfectly happy with your solution. The two dictionaries are not the same, they are distinct, so I don't see the benefit in modifying the original. I would reduce by a line though:
dic2 = {}
dic = {0: [4, 4, 4, 4, 5], 1: [3, 4, 4, 4]}
for key, value in dic.items():
dic2[key] = min(value)
print(dic2)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.