Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.3k views
in Technique[技术] by (71.8m points)

loops - Getting maximum value of each key in Python?

I'm working on a problem in which I have one dictionary, but there exist duplicate keys within it. The goal is to get the maximum value of each corresponding key, but I am confused about how to do this because the previous examples I've seen show how to get the maximum value from the dictionary as a whole. Is there a way to compare one key with the rest of the keys, see if it is a match, and then examine their values? This is what I have tried so far:

# Create mock dictionary with data
gene_data = {'geneA': 1, 
    'geneB': 2, 
    'geneC': 0,
    'geneA': 3,
    'geneB': 1,
    'geneC': 4
}

# Pass in your dictionary as the parameter.
# Return a newly created dictionary that displays each key once, alongside the maximum value.
# For our example, our expected outcome is:
# new_dict = {'geneA': 3, 'geneB': 2, 'geneC': 4}
def get_max_value_from_data(data):
    new_dict = dict()
    for key, value in data.items():
        for i in range(0, len(data)):
            if key == data.keys()[i]:
                if value < data.values()[i]:
                    new_dict[key] = value
    return new_dict
    
get_max_value_from_data(gene_data)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神解答

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...