简体   繁体   中英

Getting the max value from dictionary

So these is how my key value looks like

    dict_info = {}
    dict_info['math 12345'] = 10
    dict_info['math 1234'] = 2
    dict_info['math 123'] = 1
    dict_info['SCI 124'] = 16
    dict_info['SCI 345'] = 2

So there I have five different dictionaries. However what I want to do is make sure I compare the first letter before space for instance I have 3 math there and 2 SCI. I just want to get the highest value of 10 which represents MATH 12345. And get 16 which represents SCI 124 and skip the rest. So all I want is the highest value of classes called math and SCI. And get rid of the ones that is less in value. So far my code looks like this. I couldn't figure the syntax.

def check_if_works():
    import operator
    dict_info = {}
    dict_info['math 12345'] = 10
    dict_info['math 1234'] = 2
    dict_info['math 123'] = 1
    dict_info['SCI 124'] = 16
    dict_info['SCI 345'] = 2
    for key, value in dict_info.iteritems():
        arr = key.split(' ')
        class_first_letters_only = arr[0]
        if class_first_letters_only == arr[0]:



check_if_works()

@user161151 Here is the code but it prints me all the duplicates in my json file.

for key,value in new_dictionary.iteritems():
                                            #print key
                                            k = key.split()[0]
                                            full_info = k + ' ' + key.split()[-1]
                                            print full_info
                                            if ans.get(k,0) < value:
                                                ans[k] = value

                                        #print new_dictionary
                                                sort_info = sorted(ans.items(), key=itemgetter(1,0), reverse=True)
                                                first_20 = sort_info[:20]       

        with open('output_1.json','wb') as outfile:
                json.dump(first_20,outfile,indent=4)

I'd like to also as for my output would want full key name instead of just prefix like MATH i'd want MATH 12345 : 16. Also I'd like to save my output to a json file where it's sorted from max to minimum value pair. @Jankos Frankas

for key, value in new_dictionary.iteritems():
                                            try:
                                                if result[key.split()[0]] < value:
                                                    result[key.split()[0]] = value
                                                    keys[key.split()[0]] = key
                                            except KeyError:
                                                result[key.split()[0]] = value
                                                keys[key.split()[0]] = key
                                        #replace the key prefixes with full length key
                                        for key in keys.keys():
                                            result[keys[key]] = result.pop(key)
                                        #return result
                        with open('output_check_123.json','wb') as outfile:
                            outfile.write(json.dumps(new_dictionary,indent=4))

There's the code.

Returns the maximum values of every unique first word in the keys of dict_info as a dictionary of the key with the maximum value corresponding to that first word in dict_info .

def get_max_groups(dict_info):
    result = {}
    for key, value in dict_info.iteritems():
        sub_key = key.split()[0]
        match_keys = filter(lambda ikey: ikey.split()[0] == sub_key, result)
        if not match_keys:
            result[key] = value
            continue
        m = match_keys[0]
        if result[m] < value:
            del result[m]
            ans[key] = value
    return ans

Use max with some list comprehension :

dict_info = {}
dict_info['math 12345'] = 10
dict_info['math 1234'] = 2
dict_info['math 123'] = 1
dict_info['SCI 124'] = 16
dict_info['SCI 345'] = 2

def check_if_works(dictionary):
    math_max = max([dictionary[key] for key in dictionary if key.startswith('math')])
    sci_max = max([dictionary[key] for key in dictionary if key.startswith('SCI')])
    return math_max, sci_max


print check_if_works(dict_info)

try this:

def check_if_works():
    import operator
    dict_info = {}
    dict_info['math 12345'] = 10
    dict_info['math 1234'] = 2
    dict_info['math 123'] = 1
    dict_info['SCI 124'] = 16
    dict_info['SCI 345'] = 2
    result={}
    for key, value in dict_info.iteritems():
        try:
            if result[key.split()[0]] < value:
                result[key.split()[0]] = value
        except KeyError:
            result[key.split()[0]] = value

    return result



dict_info = check_if_works()
print dict_info

now dict_info equals:

{'SCI': 16, 'math': 10}

if you want the full length key, not only the "prefix" use this code:

def check_if_works():
    import operator
    dict_info = {}
    dict_info['math 12345'] = 10
    dict_info['math 1234'] = 2
    dict_info['math 123'] = 1
    dict_info['SCI 124'] = 16
    dict_info['SCI 345'] = 2
    result={}
    keys = {}
    for key, value in dict_info.iteritems():
        try:
            if result[key.split()[0]] < value:
                result[key.split()[0]] = value
                keys[key.split()[0]] = key
        except KeyError:
            result[key.split()[0]] = value
            keys[key.split()[0]] = key
    #replace the key prefixes with full length key
    for key in keys.keys():
        result[keys[key]] = result.pop(key)
    return result



dict_info = check_if_works()
print dict_info

resul:

{'math 12345': 10, 'SCI 124': 16}

def check_duplicates(dict_info):
    import operator

    result={}
    keys = {}
    for key, value in dict_info.iteritems():
        try:
            #print result[key.split()[0]]
            if result[key.split()[0]] < value:
                result[key.split()[0]] = value
                keys[key.split()[0]] = key
        except KeyError:
            result[key.split()[0]] = value
            keys[key.split()[0]] = key
    #replace the key prefixes with full length key
    for key in keys.keys():
        result[keys[key]] = result.pop(key)
    return result

This worked great thanks to @Jankos. I added an argument called dict_info where I can just use this function to make it work under my main script which has the same formatting of dictionary as presented. Now it works flawlessly, thank you!

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