[英]Removing elements from a dictionary consisting of tuples calculating the last element in the tuple and the value in the dictionary
给出以下字典:
a = {('a','b', 'c'):3,('a','d','c'):4, ('f','e','b'):5, ('r','t','b'):5.1}
字典由作为键的元组和作为值的数字组成。 每个元组由一系列字母组成。 从最后一个元素相同的所有元组中,应该排除那些字典值最低的元组。 例如元组('a','b', 'c')
和元组('a','d','c')
都将字母C
作为最后一个元素,因此其值为最低的应该被删除。 参考上面的字典,结果应该是:
{('a','d','c'):4, ('r','t','b'):5.1}
你可以这样做:
from collections import defaultdict
from operator import itemgetter
a = {('a','b', 'c'):3,('a','d','c'):4, ('f','e','b'):5, ('r','t','b'):5.1}
# group the items by the last element of the key of the tuple
lookup = defaultdict(list)
for key, value in a.items():
lookup[key[2]].append((key, value))
# find the maximum in each group by the value of the tuple
result = dict(max(value, key=itemgetter(1)) for value in lookup.values())
print(result)
Output
{('a', 'd', 'c'): 4, ('r', 't', 'b'): 5.1}
代码:
a = {('a','b', 'c'):3,('a','d','c'):4, ('f','e','b'):5, ('r','t','b'):5.1}
keys_to_remove = []
for key in a.keys():
srch_key = key[-1]
lowest_val = min(v for k,v in a.items() if k[-1] == srch_key)
keys_to_remove.append(*(k for k,v in a.items() if k[-1] == srch_key and v == lowest_val))
for key_to_remove in set(keys_to_remove):
a.pop(key_to_remove)
print(a)
Output:
{('a', 'd', 'c'): 4, ('r', 't', 'b'): 5.1}
另一个解决方案可能是:
a_dict = {('a','b', 'c'):3,('a','d','c'):4, ('f','e','b'):5, ('r','t','b'):5.1}
b_dict = dict()
seq = 2
for key in a_dict:
b_key = find_key(b_dict, key[seq])
if b_key is not None:
b_dict.pop(b_key)
b_dict[key] = a_dict[key]
else:
b_dict[key] = a_dict[key]
def find_key(x_dict, k, seq=2):
for key in x_dict:
if key[seq] == k:
return key
return None
创建一个空字典。 遍历字典,在新字典中搜索关键元组的最后一个元素。 如果不存在,则将键:值添加到新字典。 如果找到任何,请检查其值是否更大。 如果不是,则删除该元素并添加新的键:值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.