Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.8k 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...