Sorting by value in a python dictionary? [duplicate] - python

This question already has answers here:
How do I sort a dictionary by value?
(34 answers)
Closed 8 years ago.
I have an assignment in which a series of items and the amount a store carries of that item is given which I then have to put into a dictionary and display with the highest amount of stock to the lowest amount of stock.
The dictionary looks a bit like this:
items = {'socks': 10, 'hammers': 33, 'keyboards': 56}
and the output would look like this:
keyboards: 56
hammers: 33
socks: 10
After getting the dictionary set up, I'm having difficulty with the second part... does anyone know how I could sort by value?

It's easy to make a sorted list of (key, value) pairs:
import operator
slop = sorted(thelist.items(), key=operator.itemgetter(1), reverse=True)
and then you can loop over it to display it, e.g in Python 2:
for k, v in slop:
print '{}: {}'.format(k, v),
print

To sort you can use sorted method:
items = {'socks': 10, 'hammers': 33, 'keyboards': 56}
sorted_items = sorted(items.items(), key=lambda v: v[1], reverse = True)
As a key you specify to sort by value in the items dict. And to print it, you can just use:
for k,v in sorted_items:
print("{}:{}".format(k,v))

Related

How do you sort a dictionary by key from highest to lowest [duplicate]

This question already has answers here:
python dictionary sorting in descending order based on values
(12 answers)
Closed 4 months ago.
Hi I have a dictionary that is currently the one below:
dictionary={1:'a',2:'b',3:'c'}
my desired output is to have a dictionary with the highest keys to the left and the lowest keys to the right like below:
dictionary={3:'c',2:'b',1:'a'}
how do you do that in python 3.7?
dict(sorted(dictionary.items(), reverse=True))
This is duplicate of How do I sort a dictionary by key?
You want to get the keys from the dictionary with dictionary.keys(), then sort it in reverse with sorted(dictionary.keys(), reverse=True), and then you can use that in a dictionary comprehension:
{k: dictionary[k] for k in sorted(dictionary.keys(), reverse=True)}
# {3: 'c', 2: 'b', 1: 'a'}
Of course, if we use sorted on a dict it will return the sorted keys anyway, so we can simplify this slightly to:
{k: dictionary[k] for k in sorted(dictionary, reverse=True)}
# {3: 'c', 2: 'b', 1: 'a'}
This does seems like an XY problem, though. You may want to consider why it matters what order the keys are in? How does that affect your program?

How to get the key from value in a dictionary in Python? [duplicate]

This question already has answers here:
Get key by value in dictionary
(43 answers)
Closed 5 years ago.
d[key] = value
but how to get the keys from value?
For example:
a = {"horse": 4, "hot": 10, "hangover": 1, "hugs": 10}
b = 10
print(do_something with 10 to get ["hot", "hugs"])
You can write a list comprehension to pull out the matching keys.
print([k for k,v in a.items() if v == b])
Something like this can do it:
for key, value in a.iteritems():
if value == 10:
print key
If you want to save the associated keys to a value in a list, you edit the above example as follows:
keys = []
for key, value in a.iteritems():
if value == 10:
print key
keys.append(key)
You can also do that in a list comprehension as pointed out in an other answer.
b = 10
keys = [key for key, value in a.iteritems() if value == b]
Note that in python 3, dict.items is equivalent to dict.iteritems in python 2, check this for more details: What is the difference between dict.items() and dict.iteritems()?

how can I sort dictionary whose key is tuple and value is int? [duplicate]

This question already has answers here:
How do I sort a dictionary by value?
(34 answers)
Closed 6 years ago.
I have a dictionary like prob = {('be', 'limited'): 0.004, ('the', 'book'): 0.000432, ......}
for sorting I used
for k, v in sorted(prob, key = lambda x: x[1], reverse = True):
print k, v
but it doesn't give the result. ( it just gave me the tuples..) I wanna sort that dictionary according to value.
You should call sorted with prob.items() otherwise it returns just the keys after sorting takes place.
sorted(prob.items(), key = lambda x: x[1], reverse = True)
You can store it into collection.OrderedDict which remembers the order in which the items were added:
>>> dct = sorted(prob.items(), key=lambda x: x[1], reverse=True)
>>> result = collections.OrderedDict(dct)

sort dict by value python [duplicate]

This question already has answers here:
How do I sort a dictionary by value?
(34 answers)
Closed 3 years ago.
Assume that I have a dict.
data = {1:'b', 2:'a'}
And I want to sort data by 'b' and 'a' so I get the result
'a','b'
How do I do that?
Any ideas?
To get the values use
sorted(data.values())
To get the matching keys, use a key function
sorted(data, key=data.get)
To get a list of tuples ordered by value
sorted(data.items(), key=lambda x:x[1])
Related: see the discussion here: Dictionaries are ordered in Python 3.6+
If you actually want to sort the dictionary instead of just obtaining a sorted list use collections.OrderedDict
>>> from collections import OrderedDict
>>> from operator import itemgetter
>>> data = {1: 'b', 2: 'a'}
>>> d = OrderedDict(sorted(data.items(), key=itemgetter(1)))
>>> d
OrderedDict([(2, 'a'), (1, 'b')])
>>> d.values()
['a', 'b']
From your comment to gnibbler answer, i'd say you want a list of pairs of key-value sorted by value:
sorted(data.items(), key=lambda x:x[1])
Thanks for all answers.
You are all my heros ;-)
Did in the end something like this:
d = sorted(data, key = data.get)
for key in d:
text = data[key]
Sort the values:
sorted(data.values())
returns
['a','b']
I also think it is important to note that Python dict object type is a hash table (more on this here), and thus is not capable of being sorted without converting its keys/values to lists. What this allows is dict item retrieval in constant time O(1), no matter the size/number of elements in a dictionary.
Having said that, once you sort its keys - sorted(data.keys()), or values - sorted(data.values()), you can then use that list to access keys/values in design patterns such as these:
for sortedKey in sorted(dictionary):
print dictionary[sortedKeY] # gives the values sorted by key
for sortedValue in sorted(dictionary.values()):
print sortedValue # gives the values sorted by value
Hope this helps.
You could created sorted list from Values and rebuild the dictionary:
myDictionary={"two":"2", "one":"1", "five":"5", "1four":"4"}
newDictionary={}
sortedList=sorted(myDictionary.values())
for sortedKey in sortedList:
for key, value in myDictionary.items():
if value==sortedKey:
newDictionary[key]=value
Output: newDictionary={'one': '1', 'two': '2', '1four': '4', 'five': '5'}
In your comment in response to John, you suggest that you want the keys and values of the dictionary, not just the values.
PEP 256 suggests this for sorting a dictionary by values.
import operator
sorted(d.iteritems(), key=operator.itemgetter(1))
If you want descending order, do this
sorted(d.iteritems(), key=itemgetter(1), reverse=True)
no lambda method
# sort dictionary by value
d = {'a1': 'fsdfds', 'g5': 'aa3432ff', 'ca':'zz23432'}
def getkeybyvalue(d,i):
for k, v in d.items():
if v == i:
return (k)
sortvaluelist = sorted(d.values())
sortresult ={}
for i1 in sortvaluelist:
key = getkeybyvalue(d,i1)
sortresult[key] = i1
print ('=====sort by value=====')
print (sortresult)
print ('=======================')

sort values and return list of keys from dict python [duplicate]

This question already has answers here:
How to sort a Python dict's keys by value
(5 answers)
Closed last month.
I have a dictionary like A = {'Name1':34, 'Name2': 12, 'Name6': 46,....}.
How can I get a list of keys sorted by the values, i.e. [Name2, Name1, Name6....]?
Use sorted with the get method as a key (dictionary keys can be accessed by iterating):
sorted(A, key=A.get)
Use sorted's key argument
sorted(d, key=d.get)
sorted(a.keys(), key=a.get)
This sorts the keys, and for each key, uses a.get to find the value to use as its sort value.
I'd use:
items = dict.items()
items.sort(key=lambda item: (item[1], item[0]))
sorted_keys = [ item[0] for item in items ]
The key argument to sort is a callable that returns the sort key to use. In this case, I'm returning a tuple of (value, key), but you could just return the value (ie, key=lambda item: item[1]) if you'd like.

Categories

Resources