Elhanan Schwarts
Elhanan Schwarts

Reputation: 383

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. With reference to the above dictionary the result should be:

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

Upvotes: 0

Views: 47

Answers (3)

ibilgen
ibilgen

Reputation: 480

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.

Upvotes: 0

Aaj Kaal
Aaj Kaal

Reputation: 1284

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:

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

Upvotes: 0

Dani Mesejo
Dani Mesejo

Reputation: 61910

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

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

Upvotes: 1

Related Questions