Pythonic way to find lowest value in dictionary with list as values - python-3.x

I have a dictionary with values as list. In the given dictionary I want to find the lowest number (for every item in the list considering the value at index 0). I have written a script and works fine, but I am looking for a more Pythonic way to solve this.
c={'Apple': ['210-219', '246-255'], 'Orange': ['159-161', '202-204', '207-209', '209-211', '220-222', '238-240', '245-247', '261-263']}
loweststart=[]
for ckey, cvalue in c.items():
for i in cvalue:
print (i.split('-')[0])
start=int(i.split('-')[0])
loweststart.append(start)
print (loweststart)
print ('The lowest:',min(loweststart))

A pythonic way:
min_list = [int(element.split('-')[0]) for value in c.values() for element in value]
print(min(min_list))

You can use the min function with a generator expression that iterates through the items in the sub-lists of the dict and outputs the integer values of the first tokens in the strings:
min(int(s[:s.find('-')]) for l in c.values() for s in l)
Using a generator expression is more efficient because it avoids the need to create a temporary list to store all the values extracted from the sub-lists.

As much as I hate the adjective Pythonic, this would seem to qualify:
min([min([int(i.split('-')[0]) for i in ci[1]]) for ci in c.items()])
(The logic is slightly different than the original, in that it finds the minimum of each list, then the minimum of those minima, but the end result is the same.)

Related

Python - how to recursively search a variable substring in texts that are elements of a list

let me explain better what I mean in the title.
Examples of strings where to search (i.e. strings of variable lengths
each one is an element of a list; very large in reality):
STRINGS = ['sftrkpilotndkpilotllptptpyrh', 'ffftapilotdfmmmbtyrtdll', 'gftttepncvjspwqbbqbthpilotou', 'htfrpilotrtubbbfelnxcdcz']
The substring to find, which I know is for sure:
contained in each element of STRINGS
is also contained in a SOURCE string
is of a certain fixed LENGTH (5 characters in this example).
SOURCE = ['gfrtewwxadasvpbepilotzxxndffc']
I am trying to write a Python3 program that finds this hidden word of 5 characters that is in SOURCE and at what position(s) it occurs in each element of STRINGS.
I am also trying to store the results in an array or a dictionary (I do not know what is more convenient at the moment).
Moreover, I need to perform other searches of the same type but with different LENGTH values, so this value should be provided by a variable in order to be of more general use.
I know that the first point has been already solved in previous posts, but
never (as far as I know) together with the second point, which is the part of the code I could not be able to deal with successfully (I do not post my code because I know it is just too far from being fixable).
Any help from this great community is highly appreciated.
-- Maurizio
You can iterate over the source string and for each sub-string use the re module to find the positions within each of the other strings. Then if at least one occurrence was found for each of the strings, yield the result:
import re
def find(source, strings, length):
for i in range(len(source) - length):
sub = source[i:i+length]
positions = {}
for s in strings:
# positions[s] = [m.start() for m in re.finditer(re.escape(sub), s)]
positions[s] = [i for i in range(len(s)) if s.startswith(sub, i)] # Using built-in functions.
if not positions[s]:
break
else:
yield sub, positions
And the generator can be used as illustrated in the following example:
import pprint
pprint.pprint(dict(find(
source='gfrtewwxadasvpbepilotzxxndffc',
strings=['sftrkpilotndkpilotllptptpyrh',
'ffftapilotdfmmmbtyrtdll',
'gftttepncvjspwqbbqbthpilotou',
'htfrpilotrtubbbfelnxcdcz'],
length=5
)))
which produces the following output:
{'pilot': {'ffftapilotdfmmmbtyrtdll': [5],
'gftttepncvjspwqbbqbthpilotou': [21],
'htfrpilotrtubbbfelnxcdcz': [4],
'sftrkpilotndkpilotllptptpyrh': [5, 13]}}

How to access the count value of a Counter object in Python3?

Scenario
Given a few lines of code, I have included the line
counts = Counter(rank for rank in ranks)
because I want to find the highest count of a character in a string.
So I end up with the following object:
Counter({'A': 4, 'K': 1})
Here, the value I'm looking for is 4, because it is the highest count. Assume the object is called counts, then max(counts) returns 'K', presumably because 'K' > 'A' in unicode.
Question
How can I access the largest count/value, rather than the "largest" key?
You can use max as suggested by others. Note, though, that the Counter class provides the most_common(k) method which is slightly more flexible:
counts.most_common(1)[0][1]
Its real performance benefits, however, will only be seen if you want more than 1 most common element.
Maybe
max(counts.values())
would work?
From the Python documentation:
A Counter is a dict subclass for counting hashable objects. It is a collection where elements are stored as dictionary keys and their counts are stored as dictionary values.
So you should treat the counter as a dictionary. To take the biggest value, use max() on the counters .value().

Getting a "list index can't be a float" error when i use the same iterator from a loop in an if statment in Python 3.4

I try to iterate through a list and check each value if it is a negative number, using the following code :
for i in listy:
if (listy[i]<0):...
For some reason, python tries to evaluate listy[0.5]<0, which is the 1st item on the list. How can I fix this ?
i is the value not the index.
This line is not what you want (listy[i]<0).
You probably meant to do i<0
(listy[i]<0) is trying to use the value as the index. In you list the value is a float which can't be used as an index.
If you really want to use the index you could do:
for i in range(len(listy)):
if listy[i] < 0:
#do something
In C and many other languages, you often use the length of an array when iterating through it. You can do this in Python as well but you can also iterate through the elements without explicitly using the index (position). You seem to be mixing the two approaches and therefore you get an unexpected result.
This will iterate through the values only:
for i in listy:
# here, i is the value of the list entry
print(i)
This will use the length of the list and the index (position):
for i in range(len(listy)):
# here, i is the index (position) of the list entry, not the value
print(listy[i])
This will give you both index and value:
for i, val in enumerate(listy):
# here, i is the index (position) and val is the value
print(i, val)

How to add one to he last value in a list Python

Im fairly new to python and want to know how to add one to the last value in a list such as [1,5,9] or [44,45,20] I know it needs a for loop somewhere but how?
you can do this my_list[-1] += 1 .
the negative index let you start from the ending of a list (or any other iterable object), so -1 index is the last element in your list.
If by "adding" you mean arithmetic addition (i.e. +), do:
mylist[-1] += 1
If by "adding" you mean appending a new item to the list, do:
mylist.append(1)

Pass a string and compare it to a list

I am passsing an argument through robot framework. The argument is a string. "Detroit".
I want the code to break down that string to "D", "De", "Det", "Detr", "Detro","Detroi", and "Detroit". Of course if another string is entered, say "Flint" it would only break it down into the 5 elements. F, Fl, Fli, Flin, Flint.
(Pseudo Code)
def checkCity (self, x):
(take x which is the string, and make it a list of elements containing the letters as above).
(Then take each element and check it against data provided by the device(using a loop for each iteration)
(Once any of the elements are matched to the data, return another function that acts as a key press)
I'm familiar enough with python (and programming) in general to have the theory, just don't know how to code it.
I'm not familiar with the programming language that you are using but I will help out as much as I can.
For breaking down the string, you could use a while loop or a for loop, whichever you prefer. The ending condition being the length of the string that you put into the second parameter. In the loop, you can use substring method to break down the string and store each element into an array list.
Then for checking if any of the elements are matched, you would (as you have said) use a loop for each iteration.
In python you can access individual parts of a string by using
string[5:7]
That would give the 5th and 6th characters
This function in python will return a list like the one you want
def toSubLists(string):
sublists = []
for i in range(1, len(string)+1):
sublists.append(string[0:i])
return sublists

Resources