This question already has answers here:
Getting key with maximum value in dictionary?
(29 answers)
Closed 7 years ago.
{'19': 3, '18': 7}
If I have a list like above, how do I find the max value and then print the key, value pair like:
(['18'], 7)
print max(data.iteritems(),key=lambda x:x[-1])
maybe? Im not really sure to be honest
There are more Pythonic ways to do these things, but I hope this illustrates the steps clearly for you. First we reverse the dictionary. Find the maximum
data = {'19': 3, '18': 7}
data_rev = dict([(value, key) for (key,value) in data.iteritems()])
print data_rev
max_val = max(data_rev.keys())
If you want to see it in a single statement:
out_tuple = ([dict([(value, key) for (key,value) in data.iteritems()])[max(data.values())]], max(data.values()))
The most straightforward method would be to just iterate and find it:
max_pair = None
for k,v in thedict.items():
if (max_pair is None) or (v > max_pair[1]):
max_pair = (k,v)
print max_pair
But the standard library provides some more "pythonic" ways to get at the same information..
from functools import partial
from operator import itemgetter
print max(thedict.items(), key=partial(itemgetter, 1))
This assumes you only want to get the first key where the max value appears. If instead you want all keys where the max value appears you have to do it in two passes (once to find the max, once to find all the keys).
max_val = max(thedict.values())
max_pair = (tuple(k for k in thedict if thedict[k] == max_val), max_val)
Related
This question already has an answer here:
How to iterate `dict` with `enumerate` and unpack the index, key, and value along with iteration
(1 answer)
Closed 3 months ago.
I am looking for a way to get the current loop iteration while looping though a key, value pair of dictionary items.
currently i am using enumerate() to split it into iteration, tuple(key, value) however this requires using tuple indexes to split it back out.
mydict = {'fruit':'apple', 'veg':'potato', 'sweet':'haribo'}
for i, kv in enumerate(mydict.items()):
print(f"iteration={i}, key={kv[0]}, value={kv[1]}")
#>>> iteration=0, key=fruit, value=apple
#>>> iteration=1, key=veg, value=potato
#>>> iteration=2, key=sweet, value=haribo
what I am looking for is a better method to replace the following:
i = 0
for key, value in mydict.items():
print(f"iteration={i}, key={key}, value={value}")
i+=1
#>>> iteration=0, key=fruit, value=apple
#>>> iteration=1, key=veg, value=potato
#>>> iteration=2, key=sweet, value=haribo
I do not want to give up user assigned keywords for the dictionary just to include iteration. I am hoping to find a solution similar to (psudo-code):
for key, value, iteration in (tuple(mydict.items()), list(mydict.keys()).index(k)):
Just put the (key, value) in brackets:
mydict = {'fruit':'apple', 'veg':'potato', 'sweet':'haribo'}
for i, (key, value) in enumerate(mydict.items()):
print(f"iteration={i}, key={key}, value={value}")
This question already has answers here:
How can I calculate average of different values in each key of python dictionary?
(3 answers)
Closed 2 years ago.
I have an existing dictionary called StudentGrad that has the following data type:
('Aditya','male','senior'):[0.83,0.87,0.82,0.83],
('Varun','male','senior'):[0.76,0.86,0.88,0.79],
('Shantanu','male','senior'):[0.79,0.81,0.78,0.78],
I want to create a new dictionary called studentAvg that has the same keys, but returns an average grade for the values:
('Aditya','male','senior'):[0.84],
('Varun','male','senior'):[0.82],
('Shantanu','male','senior'):[0.79],
Any help would be appreciated....
Thanks!
Try to do this:
x = {('Aditya','male','senior'):[0.83,0.87,0.82,0.83],
('Varun','male','senior'):[0.76,0.86,0.88,0.79],
('Shantanu','male','senior'):[0.79,0.81,0.78,0.78]}
def average(data):
sum = 0
for elem in data:
sum+=elem
result = sum/len(data)
return result
y = {}
for elem in x:
y[elem] = average(x[elem])
You can use a dict comprehension and a custom function for averaging :
d1 = {('Aditya','male','senior'):[0.83,0.87,0.82,0.83],
('Varun','male','senior'):[0.76,0.86,0.88,0.79],
('Shantanu','male','senior'):[0.79,0.81,0.78,0.78],
}
def average(list_values):
"let's assume you want an arithmetic mean"
return sum(list_values) / len(list_values)
d2 = {k:average(val) for k, val in d1.items()}
And if you really want a list of the average (as stated in the question) :
d2 = {k:[average(val)] for k, val in d1.items()}
Try this:
studentAvg = {
('Aditya','male','senior'):sum(studendGrad["('Aditya','male','senior')"])/len(studendGrad["('Aditya','male','senior')"]),
('Varun','male','senior'):sum(studentGrad["(Varun','male','senior')"])/len(studentGrad["('Varun','male','senior')"]),
('Shantanu','male','senior'):sum(studentGrad["('Shantanu','male','senior')"]/len(studentGrad["('Shantanu','male','senior')"])
}
This question already has answers here:
initialize and add value to a list in dictionary at one step in Python 3.7
(2 answers)
Closed 2 years ago.
I usually do this if check:
new_value = 'xxx'
if key in my_dict:
values = my_dict[key]
values.append(new_value)
my_dict[key] = values
else:
my_dict[key] = [new_value]
I feel there may be a more concise way to do this, but I always do this.
Use setdefault
mydict.setdefault('xxx', []).append(new_value)
Syntax
dict.setdefault(key, default=None)
key: This is the key to be searched.
default: This is the Value to be returned in case key is not found.
defaultdicts are what you need.
from collections import defaultdict
my_dict = defaultdict(list)
my_dict['key'].append('value')
my_dict
#defaultdict(<class 'list'>, {'key': ['value']})
You could cut out a couple of lines by skipping straight to the append:
new_value = 'xxx'
if key in my_dict:
my_dict[key].append(new_value)
else:
my_dict[key] = [new_value]
For example lets say we have the following dictionary:
dictionary = {'A':4,
'B':6,
'C':-2,
'D':-8}
How can you print a certain key given its value?
print(dictionary.get('A')) #This will print 4
How can you do it backwards? i.e. instead of getting a value by referencing the key, getting a key by referencing the value.
I don't believe there is a way to do it. It's not how a dictionary is intended to be used...
Instead, you'll have to do something similar to this.
for key, value in dictionary.items():
if 4 == value:
print key
In Python 3:
# A simple dictionary
x = {'X':"yes", 'Y':"no", 'Z':"ok"}
# To print a specific key (for instance the 2nd key which is at position 1)
print([key for key in x.keys()][1])
Output:
Y
The dictionary is organized by: key -> value
If you try to go: value -> key
Then you have a few problems; duplicates, and also sometimes a dictionary holds large (or unhashable) objects which you would not want to have as a key.
However, if you still want to do this, you can do so easily by iterating over the dicts keys and values and matching them as follows:
def method(dict, value):
for k, v in dict.iteritems():
if v == value:
yield k
# this is an iterator, example:
>>> d = {'a':1, 'b':2}
>>> for r in method(d, 2):
print r
b
As noted in a comment, the whole thing can be written as a generator expression:
def method(dict, value):
return (k for k,v in dict.iteritems() if v == value)
Python versions note: in Python 3+ you can use dict.items() instead of dict.iteritems()
target_key = 4
for i in dictionary:
if dictionary[i]==target_key:
print(i)
Within a dictionary if you have to find the KEY for the highest VALUE please do the following :
Step 1: Extract all the VALUES into a list and find the Max of list
Step 2: Find the KEY for the particular VALUE from Step 1
The visual analyzer of this code is available in this link : LINK
dictionary = {'A':4,
'B':6,
'C':-2,
'D':-8}
lis=dictionary.values()
print(max(lis))
for key,val in dictionary.items() :
if val == max(lis) :
print("The highest KEY in the dictionary is ",key)
I think this is way easier if you use the position of that value within the dictionary.
dictionary = {'A':4,
'B':6,
'C':-2,
'D':-8}
# list out keys and values separately
key_list = list(dictionary.keys())
val_list = list(dictionary.values())
# print key with val 4
position = val_list.index(4)
print(key_list[position])
# print key with val 6
position = val_list.index(6)
print(key_list[position])
# one-liner
print(list(my_dict.keys())[list(my_dict.values()).index(6)])
Hey i was stuck on a thing with this for ages, all you have to do is swap the key with the value e.g.
Dictionary = {'Bob':14}
you would change it to
Dictionary ={1:'Bob'}
or vice versa to set the key as the value and the value as the key so you can get the thing you want
This question already has answers here:
Two way/reverse map [duplicate]
(15 answers)
Closed 10 years ago.
dictionary is usually good for find value by key,but find key by value is pretty slow
for k,v in dictionary.items():
if v = myValue:
return k
is there already a data structure that make both key->value and ke
You could try bidict:
>>> husbands2wives = bidict({'john': 'jackie'})
>>> husbands2wives['john'] # the forward mapping is just like with dict
'jackie'
>>> husbands2wives[:'jackie'] # use slice for the inverse mapping
'john'
Just create an inverted mapping:
from collections import defaultdict
inverted = defaultdict(list)
for k, v in dictionary.iteritems():
inverted[v].append(k)
Note that the above code handles duplicate values; inverted[v] returns a list of keys that hold that value.
If your values are also unique, a simple dict can be used instead of defaultdict:
inverted = { v: k for k, v in dictionary.iteritems() }
or, in python 3, where items() is a dictionary view:
inverted = { v: k for k, v in dictionary.items() }
Python 3:
revdict = {v:k for k,v in dictionary.items()}
(Python 2 use .iteritems() instead)