Reputation: 69
maxValue = int(list(ab.keys())[i].split()[1])
for i in range(1, len(list(ab.keys()))):
if maxValue > int(list(ab.keys())[i].split()[1]):
maxValue = int(list(ab.keys())[i].split()[1])
sb = maxValue
maxValue = int(list(ab.keys())[i].split()[0])
for i in range(1, len(list(ab.keys()))):
if maxValue > int(list(ab.keys())[i].split()[0]):
maxValue = int(list(ab.keys())[i].split()[0])
sa = maxValue
maxValue = int(list(ab.keys())[i].split()[1])
for i in range(1, len(list(ab.keys()))):
if maxValue < int(list(ab.keys())[i].split()[1]):
maxValue = int(list(ab.keys())[i].split()[1])
bb = maxValue
maxValue = int(list(ab.keys())[i].split()[0])
for i in range(1, len(list(ab.keys()))):
if maxValue < int(list(ab.keys())[i].split()[0]):
maxValue = int(list(ab.keys())[i].split()[0])
ba = maxValue
i used to use this method, but i take too much time and i cannot use max(ab) cause my key look like this
ab = {"1 3":1, "2 3":2, "3 4":3}
Upvotes: 0
Views: 86
Reputation: 1302
You can find largest key using,
max([i.replace(' ','') for i in ab.keys()])
If you need as int
, use the following code.
max([int(i.replace(' ','')) for i in ab.keys()])
Upvotes: 1
Reputation: 6298
Finding the maximal number in the keys (based on the original code posted in the question, where keys are split, and maxValue
is a number):
import itertools
ab = {"1 3":1, "2 3":2, "3 4":3}
# Splitting keys to numbers
# [['1', '3'], ['2', '3'], ['3', '4']]
x = [k.split() for k in ab.keys()]
# Chaining together the lists of keys numbers
# ['1', '3', '2', '3', '3', '4']
y = list(itertools.chain(*x))
# Finiding max key
# 4
print(max([int(z) for z in y]))
One-liner:
# 4
print(max([int(z) for z in list(itertools.chain(*[k.split() for k in ab.keys()]))]))
Upvotes: 0
Reputation: 382
I guess your question is your want to find largest key. So, if
ab = {"1 3":1, "2 3":2, "3 4":3}
then you are expecting "3 4" as the result. Is my understanding correct?
I am sharing a simplified conceptual program. See if this helps:
key_list = list(ab.keys())
key_list.sort()
print(key_list[-1])
Upvotes: 1
Reputation: 82755
I believe you need max
with a custom key
Ex:
ab = {"1 3":1, "2 3":2, "3 4":3, "1 1": 4}
print(max(ab.items(), key=lambda x: tuple(map(int, x[0].split()))))
Output:
('3 4', 3)
Upvotes: 2