Minimum sum from a dictionary of lists in Python - python

I'm newish to Python (and stackoverflow)...bear with me! I have a dictionary that looks like this:
valueDict[i] = [x,y]
I want to find the minimum key based on the sum of x and y. I know for a dictionary of values I can use:
minVal = min(valueDict, key=valueDict.get)
But I don't think I can modify this approach for a dict of lists.

You can provide any function for the key argument of min. For a dictionary of values you do
minVal = min(dict, key=dict.get) # note no parentheses
If you wanted to the minimum based on the sum, you might do
minVal = min(dict, key=lambda i: sum(dict[i]))

You can use:
minVal = min(d, key=lambda x: sum(d[x]))
where d is the dict.

Related

how to get the corresponding key for the maximum value in dictionary list in the most effecient way?

Let's assume that there is a dictionary list like this one:
lst = {(1,1):2, (1,2):5, (1,3):10, (1,4):14, (1,6):22}
I want a simple (the most efficient) function that returns the dictionary key which its value is the maximum.
For example:
key_for_max_value_in_dict(lst) = (1,6)
because the tuple (1,6) has the most value (22).
I came up with this code which might be the most efficient one:
max(lst, key=lambda x: lst[x])
Use a comprehension for that like:
Code:
max((v, k) for k, v in lst.items())[1]
How does it work?
Iterate over the items() in the dict, and emit them as tuples of (value, key) with the value first in the tuple. max() can then find the largest value, because tuples sort by each element in the tuple, with first element matching first element. Then take the second element ([1]) of the max tuple since it is the key value for the max value in the dict.
Test Code:
lst = {(1,1):2, (1,2):5, (1,3):10, (1,4):14, (1,6):22}
print(max((v, k) for k, v in lst.items())[1])
Results;
(1, 6)
Assuming you're using a regular unsorted dictionary, you'll need to walk down the entire thing once. Keep track of what the largest element is and update it if you see a larger one. If it is the same, add to the list.
largest_key = []
largest_value = 0
for key, value in lst.items():
if value > largest_value:
largest_value = value
largest_key = [key]
elif value == largest_value:
largest_key.append(key)

Iteration over a sub-list of dictionaries -Python

I have a list of dictionaries e.g.:
list_d = [{"a":1},{"b":2,"c":3}]
(case 1)
for item in list_d:
# add values of each sub-list's dicts
(case 2)
for item in list_d[1]:
# add values of the specific sub-list of dict
(case1) it returns the sum of each sub-list's dict values.
(case2) returns only the keys of the dictionaries.
Is there an efficient way to get the dictionaries of the sub-list(case2) so to add the values?
Here's one way to do it:
reduce(lambda x,y: x + sum(y.values()), list_d, 0)
That is, starting with 0 (as the first x), add the sum of all values in each dict within list_d.
Here's another way:
sum(sum(x.values()) for x in list_d)
That is, sum the (sum of values for each dict in list_d).
As Antti points out it is unclear what you are asking for. I would recommend you having a look at the built-in tools in Python for Functional programming
Consider the following examples:
from operator import add
list_d = [{"a":1},{"b":2,"c":3}]
case_1 = map(lambda d: sum(d.values()), list_d)
case_2 = reduce(add, map(lambda d: sum(d.values()), list_d))

A pythonic way to sum the values of a dict with a specified key list?

Let's say I have a list (or other iterable object) ['a','b','c','d']. I have a dict X. I can sum them up in the naive way:
s = 0
for k in ['a','b','c','d']:
s += X[k]
But is there a more pythonic way?
You can do:
s = sum(X[k] for k in ['a','b','c','d'])
Yes, by using the sum function and a generator expression. You can even iterate over the characters of a string:
s = sum(X[k] for k in 'abcd')

Copying first n items of a dictionary into another dictionary

This is a simple question but I am unable to code this in python. I want to copy first n items ( supposedly 100 ) i.e both the values and keys into another empty dictionary. I'll give a more clear picture of this. I created a dictionary and sorted it using OrderedDict. My code for sorting it is :
ordP = OrderedDict(reversed(sorted(wcP.items(), key=lambda t: t[1])))
Here ordP is the ordered dictionary I got. This is in descending order. And my original dictionary is wcP. I want to put the first 100 values of ordP i.e the first 100 maximum values of ordP ( sorted according to the keys ) in a new dictionary.
Dictionaries aren't ordered, but if you just want a random selection:
new_values = dict(your_values.items()[:n])
Or, for those obsessed with laziness:
import itertools
new_values = dict(itertools.islice(your_values.iteritems(), n))
If there's a particular sort you want to impose, define a key function that takes the key and value. People usually do lambdas, but there's no reason you can't use a full function.
def example_key_func((key, value)):
return key * value
new_dict = dict(sorted(your_values.items(), key=example_key_func)[:n])
n = 100
assert len(d.keys()) >= n
dic100 = {k:v for k,v in list(d.items())[:n]}

Is there a pythonic way to grab the total amount of variables within lists inside a dict?

I have a dictionary where each key has a list (vector) of items:
from collections import defaultdict
dict = defaultdict(list)
dict[133] = [2,4,64,312]
dict[4] = [2,3,5,12,45,32]
dict[54] = [12,2,443,223]
def getTotalVectorItems(items):
total = 0
for v in items.values():
total += len(v)
return total
print getTotalVectorItems(dict)
This will print:
14 # number of items in the 3 dict keys.
Is there an easier more pythonic way other than creating this "getTotalVectorItems" function? I feel like there is a quick way to do this already.
You are looking for the sum() built-in with a generator expression:
sum(len(v) for v in items.values())
The sum() function totals the values of the given iterator, and the generator expression yields the length of each value in the lists.
Note that calling lists vectors is probably confusing to most Python programmers, unless you are using the term vector in the context of the domain of the problem.
print sum(map(len,dic.itervalues()))

Categories

Resources