Sort Python List [duplicate] - python

This question already has answers here:
sort dict by value python [duplicate]
(9 answers)
Closed 9 years ago.
I have a list, and it is currently sorted by key(A,B,C). The value is a number count of how many times the key appears in a file. The code gives results like this:
14 A
157 B
17 C
...
I need to reverse this order around. I want to sort by the value instead of key so it reads like this:
14 A
17 C
157 B
I have read and tried all the documentation I could find on here and Google. I don't think it should be too complex, but I am overthinking something.
Is there a simple solution to read the order by number value? Also every time I try to sort by value, it says 'int or str is not callable'. I don't understand what this means.
Some of my code is below:
lst = list()
for key, val in counts.items():
lst.append((key, val))
lst.sort()
for key, val in lst:
print val, key

The key argument to sort() allows you to specify the sorting key.
You could use:
lst.sort(key=lambda (k,v):v)
or, equivalently,
lst.sort(key=operator.itemgetter(1))

list.sort accept optional key parameter.
>>> counts = {
... 'A': 14,
... 'B': 157,
... 'C': 17,
... }
>>>
>>> lst = counts.items()
>>> lst.sort(key=lambda x: x[1]) # x[1] => count
>>> for key, val in lst:
... print val, key
...
14 A
17 C
157 B
According to Mutable Sequence Types:
The sort() method takes optional arguments for controlling the comparisons.
...
key specifies a function of one argument that is used to extract a
comparison key from each list element: key=str.lower. The default
value is None.

This works, assuming
import operator
for key, val in counts.items():
lst.append((key, val))
# lst should be like this :
# lst = [('A',14), ('B',157), ('C',17), ('D',12), ('E',189)]
sorted_lst = sorted(set(lst), key=operator.itemgetter(1))
print sorted_lst

Related

Dictionary get value without knowing the key

In python if I have a dictionary which has a single key value pair and if I don't know what the key might be, how can I get the value?
(and if I have a dict with more than 1 key, value pair, how can I return any one of the values without knowing any of the keys?)
You just have to use dict.values().
This will return a list containing all the values of your dictionary, without having to specify any key.
You may also be interested in:
.keys(): return a list containing the keys
.items(): return a list of tuples (key, value)
Note that in Python 3, returned value is not actually proper list but view object.
Other solution, using popitem and unpacking:
d = {"unknow_key": "value"}
_, v = d.popitem()
assert v == "value"
Further to Delgan's excellent answer, here is an example for Python 3 that demonstrates how to use the view object:
In Python 3 you can print the values, without knowing/using the keys, thus:
for item in my_dict:
print( list( item.values() )[0] )
Example:
cars = {'Toyota':['Camry','Turcel','Tundra','Tacoma'],'Ford':['Mustang','Capri','OrRepairDaily'],'Chev':['Malibu','Corvette']}
vals = list( cars.values() )
keyz = list( cars.keys() )
cnt = 0
for val in vals:
print('[_' + keyz[cnt] + '_]')
if len(val)>1:
for part in val:
print(part)
else:
print( val[0] )
cnt += 1
OUTPUT:
[_Toyota_]
Camry
Turcel
Tundra
Tacoma
[_Ford_]
Mustang
Capri
OrRepairDaily
[_Chev_]
Malibu
Corvette
That Py3 docs reference again:
https://docs.python.org/3.5/library/stdtypes.html#dict-views
Two more ways:
>>> d = {'k': 'v'}
>>> next(iter(d.values()))
'v'
>>> v, = d.values()
>>> v
'v'
One more way: looping with for/in through a dictionary we get the key(s) of the key-value pair(s), and with that, we get the value of the value.
>>>my_dict = {'a' : 25}
>>>for key in my_dict:
print(my_dict[key])
25
>>> my_other_dict = {'b': 33, 'c': 44}
>>> for key in my_other_dict:
print(my_other_dict[key])
33
44

Find max and print key, value pair of a dictionary [duplicate]

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)

Finding a key for a certain value python [duplicate]

This question already has answers here:
Get key by value in dictionary
(43 answers)
Closed 8 years ago.
If p='hello'
I need to search the dictionary for the value 'hello' and return the key for 'hello'
Is there a certain built in function that could help me do this?
I can't think of a built-in function to do this, but the best possible way would be:
def get_keys(d, x):
return [k for k, v in adict.items() if v == x]
Demo:
>>> example = {'baz': 1, 'foo': 'hello', 'bar': 4, 'qux': 'bye'}
>>> get_keys(example, 'hello')
['foo']
We use a list here because any one value can occur multiple times in a dictionary- so we need something to hold all of the applicable corresponding keys.
With that in mind, if you only want the first found instance you would just do [0] on the returned list.
You can do:
def get_pos(my_dict, my_str):
pos = []
for i in my_dict:
if my_dict[i] == my_str:
pos.append(i)
return pos
Examples
>>> a = {'apple':'hello', 'banana':'goodbye'}
>>> get_pos(a,'hello')
'apple'

If in python dictionary, multiple keys are assign to a value then how to get value by using one of the key? [duplicate]

This question already has answers here:
partial match dictionary key(of tuples) in python
(4 answers)
Closed 8 years ago.
d = dict({('a','b'):1})
then how to get value by using either d.get('a') or d.get('b') instead of d.get(('a','b'))
>>> d=dict({('a','b'):1})
>>> d.get('a') // should return value as 1
>>> d.get('b') // should return value as 1
>>> d.get(('a','b'))
1
>>>
You could make a partial match function similar to, but simpler than, the one in this question.
def partial_match(d, part_key):
for key, value in d.items():
if part_key in key:
return value
>>> partial_match(d, 'a')
1
You could create a dedicated data structure derived from dict:
>>> class MyDict(dict):
... def __init__(self, *args):
... if args and type(args[0]) is dict:
... for k, v in args[0].iteritems():
... self.__setitem__(k, v)
... dict.__init__(self, *args)
... def __setitem__(self, keys, val):
... dict.__setitem__(self, keys, val)
... if type(keys) is tuple:
... for k in keys:
... self.__setitem__(k, val)
...
>>> d=MyDict({('a','b'):1})
>>> print d.get('a')
1
>>> print d.get('b')
1
>>> print d.get(('a','b'))
1
>>>
This creates new entries in the dictionary as suggested by #Thrustmaster.
The alternative is to create a 'partial match' function as #Stuart has proposed, that uses less memory as entries are not duplicated, but using more computations as it requires looping through all keys, effectively making the key hashes useless.
As pointed out in the comments, dictionary is simply a key-value mapping. You give it a single key, it will return a uniquely identifiable value against it.
To be able to get the value from the dict using any of the elements in the tuple, then you'd need to use something like the below:
>>> def updateDict(d, obj):
... for key, value in obj.items():
... for k in key:
... d[k] = value
...
>>> res = {}
>>> updateDict(res, {('a','b'):1})
>>> res
{'a': 1, 'b': 1}
>>> res['a']
1
>>> res['b']
1
Note that the code above merely inserts the values multiple time one for each element in the tuple.
You can create the dictionary you want using the original dict:
d1 = dict({('a','b'):1})
# creates {'a':1, 'b':1 }
d2 = {x:v for k, v in d1.items() for x in k}
print d2.get('a') # prints 1
print d2.get('b') # prints 1

How can you print a key given a value in a dictionary for Python?

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

Categories