Reputation: 198
I have a dict like this
b = {'2': ['10', '5', '4'], '4': ['1', '9', '2'], '3': ['90', '87', '77'], '1': ['30']}
I need to compare each value in the list to others and return only the least value in the dict
I have tried
for k,v in b.items():
for r in range(len(v)):
print(min(v[r] + v[r]))
It is giving me a weird output! This is the output obtained from that code.
0
5
4
1
9
2
0
7
7
0
0
0
0
I need the key and value which has the least value in the entire dict output like this d = {4:[1]}
Upvotes: 0
Views: 118
Reputation: 519
What if you have multiple key value pairs with same minimum value?
This solution works fine for that as well.
result={k:min(map(int,v)) for k,v in b.items()}
minVal=min(result.values())
result={k:[minVal] for k in result.iterkeys() if result[k] == minVal}
print(result)
{'4': [1]}
for ex :
b = {'2': ['10', '5', '4'], '4': ['1', '9', '2'], '3': ['90', '1', '77'], '1': ['30']}
Output will be :
{'3': [1], '4': [1]}
Upvotes: 0
Reputation: 23
First, your list is numbers as text. I did not correct that. If you can fix that then you can take off the in() in this code.
for k, v in b.items():
x = int(min(b[k]))
try:
lowVal
except:
lowVal = x
lowKey = k
else:
if x < lowVal:
lowKey = k
lowVal = x
print('{0}: {1}'.format(lowKey, lowVal))
Edit: a word
Upvotes: 0
Reputation: 59731
Ugly one-liner:
b = {'2': ['10', '5', '4'], '4': ['1', '9', '2'], '3': ['90', '87', '77'], '1': ['30']}
result = dict([min(((int(k), [min(map(int, v))]) for k, v in b.items()), key=lambda t: t[1])])
print(result)
Output:
{4: [1]}
Breakdown:
b = {'2': ['10', '5', '4'], '4': ['1', '9', '2'], '3': ['90', '87', '77'], '1': ['30']}
# Generator of each key with its minimal element
# (here the generator would produce the list [(2, [4]), (4, [1]), (3, [77]), (1, [30])])
key_min = ((int(k), [min(map(int, v))]) for k, v in b.items())
# Pick tuple with minimal value
# (here the tuple (4, [1]) from the previous generator)
min_entry = min(key_min, key=lambda t: t[1])
# Make into dict
# (here {4: [1]}; first element of the tuple is the key and second element the value)
result = dict([min_entry])
print(result)
Upvotes: 1
Reputation: 27323
You want the minimum of minimums, or:
min({k: min(b[k], key=int) for k in b}.items(), key=lambda x: x[1])
This returns the tuple ('4', '1')
.
Upvotes: 0
Reputation: 394
If you want a straightforward answer without any confusion
min_list = {}
for k,v in b.items():
min_value = min(v)
min_list[min_value] = k
print({ min_list[min(min_list)]:min(min_list)})
Upvotes: 0
Reputation: 29089
You can do it with a dict-comprehension
{int(key): [min( int(value) for value in value_list)] for key, value_list in b.items()}
Upvotes: 0