简体   繁体   English

从由元组组成的字典中删除元素,计算元组中的最后一个元素和字典中的值

[英]Removing elements from a dictionary consisting of tuples calculating the last element in the tuple and the value in the dictionary

The following dictionary is given:给出以下字典:

a = {('a','b', 'c'):3,('a','d','c'):4, ('f','e','b'):5, ('r','t','b'):5.1}

The dictionary consists of tupels as a key and numbers as a value.字典由作为键的元组和作为值的数字组成。 Each tuple consists of a series of letters.每个元组由一系列字母组成。 From all the tuples whose last element is the same one should exclude those whose dictionary value is the lowest.从最后一个元素相同的所有元组中,应该排除那些字典值最低的元组。 For example the tuple ('a','b', 'c') and the tuple ('a','d','c') Both have the letter C as the last element, therefore the one whose value is the lowest should be removed.例如元组('a','b', 'c')和元组('a','d','c')都将字母C作为最后一个元素,因此其值为最低的应该被删除。 With reference to the above dictionary the result should be:参考上面的字典,结果应该是:

{('a','d','c'):4, ('r','t','b'):5.1}

You could do:你可以这样做:

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 Output

{('a', 'd', 'c'): 4, ('r', 't', 'b'): 5.1}

Code:代码:

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: Output:

{('a', 'd', 'c'): 4, ('r', 't', 'b'): 5.1}

Another solution might be:另一个解决方案可能是:

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

Create an empty dictionary.创建一个空字典。 Iterate over the dict, search the last element of the key tuple in new dict.遍历字典,在新字典中搜索关键元组的最后一个元素。 Add the key:value to new dict if not exists.如果不存在,则将键:值添加到新字典。 If found any, check if its value is greater or not.如果找到任何,请检查其值是否更大。 If it is not, delete the element and add the new key:value.如果不是,则删除该元素并添加新的键:值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM