How to get the key from only the value? [duplicate] - python

This question already has answers here:
Getting key with maximum value in dictionary?
(29 answers)
Closed 1 year ago.
I have this dictionary:
a_dict = {"car":5,"laptop":17,"telephone":3,"photo":14}
I would like to print the key which has the highest value.
For example, I would like to print out the key laptop because it has the highest number
I have tried this so far:
def get_oldest(things):
new_list = []
for elements in things:
new_list.append(things[element])
new_list.sort()
Now, I have sorted the list from the smallest to the highest, so I know that the last item in the list has the highest value, but how do I match that to the correct key and print that.

There is a much easier way:
a_dict = {"car": 5,"laptop": 17,"telephone": 3,"photo": 14}
oldest = max(a_dict, key=a_dict.get)
# "laptop"
This uses max with a key function. You can use max on the plain dict because iterating a dict produces its keys.

Related

How could we access the value in a dictionary that is present as a list? [duplicate]

This question already has answers here:
Finding the average of a list
(25 answers)
Find a value from a dictionary in python by taking a key from user input [closed]
(3 answers)
Closed 2 years ago.
marks={'A':[50,70,90],'B':[60,80,70],'C':[70,80,90]}
In the above dictionary, I need to access the value of B and to find the average of list (i:e:(60+80+70)/3). How could I access the value and find the average? What I tried was...
marks={'A':[50,70,90],'B':[60,80,70],'C':[70,80,90]}
get_name=input()
for i in marks:
if i==get_name:
for j in i:
add += marks[j]
print(add/3)
It shows up error. How to access the values in the dictionary of the list[60,80,70] with respect to key 'B'.
Here's a one liner -
avg = sum(marks['B'])/3
sum() will total the value in that respective list and you just have to divide it by the size of the list.
input = 'A'
average = sum(marks[input])/len(marks[input])
marks={'A':[50,70,90],'B':[60,80,70],'C':[70,80,90]}
For the above code, marks[get_name] should print out the list [60,80,70] through which the mean can be then taken.
To iterate over a dictionary you would use, for key, val in marks.items() and check if the provided user input equals to one of the key and then take the average.

Extract n top elements from dictionary [duplicate]

This question already has answers here:
5 maximum values in a python dictionary
(5 answers)
Closed 4 years ago.
I have created a dictionary in python. I have sorted the dictionary with the following instruction.
dict = {}
dict[identifier] = dst
sorted_dict = sorted(dict.items(), key=operator.itemgetter(1))
print sorted_dict
Here identifier is key and dst is a value
I want to retrieve first N elements from the dictionary. How I can do that?
Use slicing to extract n elements of the list
>>> print(sorted_dict[:n])
collectons.Counter It's the way to go:
from collections import Counter
count_dict = Counter(the_dict)
print(count_dict.most_common(n))
Here you have a live example

Get list with more elements in dictionary of lists [duplicate]

This question already has an answer here:
List as value in dictionary, get key of longest list
(1 answer)
Closed 4 years ago.
I've already seen several posts about dictionary of lists but none of them could help me so far. I have a dictionary of lists like:
dict = {'a': [1,5,4], 'b': [4], 'c': [1,5,4,3,8], 'd': [1,4]}
Now I want, in a loop, get the list with more elements, in this case the first list would be the "c" and next remove that list and start the loop again. I started by append the keys and the values of "dict" in a array (I don't know if this is necessary):
for key, value in dict.items():
array_keys.append(str(key))
array_values.append(dict[key])
Next, I tried to start the loop and to get the list with more elements I used:
max_list = max([len(i) in array_values])
With this I get "5" that is the maximum number of elements of values in the dictionary. I want to get the name of list, "c". Can you help me?
Use max() with a key function:
max(dictobject, key=lambda k: len(dictobject[k]))
This returns the key for which the value is longest.
Normally max() will compare the values of the iterable you give it, returning the element that'd be sorted last. If you pass a key function along, it'll return the value where key(value) will sort last. Here the key function returns the length of the value associated with the dictionary key.

Getting the most common key value in a list of dictionaries [duplicate]

This question already has an answer here:
python: get the most frequent value in a list of dictionaries
(1 answer)
Closed 7 years ago.
For example,
I have
myList = [{'imdb' : '12345'...}, {'imdb' : '54234'....}, {'imdb' : '12345'...}...]
I want
myList = [{'imdb' : '12345'...}, {'imdb' : '12345'...}...]
I want to get the most common imdb key value.
Thanks.
There is one question which answers how to get the most common list item, but I want the most common key value of dictionaries in a list.
This is sort of different.
from collections import Counter
most_common_imdb_value = Counter(d['imdb'] for d in myList).most_common(1)[0]
If you then need a list of those dictionaries that match the most common imdb value do:
[d for d in myList if d['imdb'] == most_common_imdb_value]

Print the key of the max value in a dictionary the pythonic way [duplicate]

This question already has answers here:
Getting key with maximum value in dictionary?
(29 answers)
Closed 6 years ago.
Given a dictionary d where the key values pair consist of a string as key and an integer as value, I want to print the key string where the value is the maximum.
Of course I can loop over d.items(), store the maximum and its key and output the latter after the for loop. But is there a more "pythonic" way just using just a max function construct like
print max(...)
print max(d.keys(), key=lambda x: d[x])
or even shorter (from comment):
print max(d, key=d.get)

Categories