简体   繁体   中英

How to find the highest value element in a list with reference to a dictionary on python

How do I code a function in python which can:

  • iterate through a list of word strings which may contain duplicate words and referencing to a dictionary,
  • find the word with the highest absolute sum, and
  • output it along with the corresponding absolute value.
  • The function also has to ignore words which are not in the dictionary.

For example,
Assume the function is called H_abs_W() .
Given the following list and dict:

list_1 = ['apples','oranges','pears','apples'] 
Dict_1 = {'apples':5.23,'pears':-7.62}

Then calling the function as:

H_abs_W(list_1,Dict_1)

Should give the output:

'apples',10.46

EDIT: I managed to do it in the end with the code below. Looking over the answers, turns out I could have done it in a shorter fashion, lol.

def H_abs_W(list_1,Dict_1):
    
    freqW = {}
    for char in list_1:
        if char in freqW:
            freqW[char] += 1
        else:
            freqW[char] = 1

    ASum_W = 0
    i_word = ''
    for a,b in freqW.items():
            x = 0
            d = Dict_1.get(a,0)
            x = abs(float(b)*float(d))
            if x > ASum_W:
                ASum_W = x
                i_word = a
       
    return(i_word,ASum_W)
list_1 = ['apples','oranges','pears','apples'] 
Dict_1 = {'apples':5.23,'pears':-7.62}

d = {k:0 for k in list_1}
for x in list_1:
    if x in Dict_1.keys():
        d[x]+=Dict_1[x]
        
m = max(Dict_1, key=Dict_1.get)
print(m,Dict_1[m])

try this,

key, value = sorted(Dict_1.items(), key = lambda x : x[1], reverse=True)[0]

print(f"{key}, {list_1.count(key) * value}")

# apples, 10.46

you can use Counter to calculate the frequency(number of occurrences) of each item in the list.

  • max(counter.values()) will give us the count of maximum occurring element
  • max(counter, key=counter.get) will give the which item in the list is associated with that highest count.

========================================================================

from collections import Counter


def H_abs_W(list_1, Dict_1):
    counter = Counter(list_1)
    count = max(counter.values())
    item = max(counter, key=counter.get)
    return item, abs(count * Dict_1.get(item))

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.

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