0

I have a dictionary like:

Data = {
    "weight_factors" : {
        "parameter1" : 10,
        "parameter2" : 30,
        "parameter3" : 30
        },
    "other_info" : {
        }
}

I want to get the sum of all values that are under the key "weight_factors":

sum = Data["weight_factors"]["parameter1"] + 
      Data["weight_factors"]["parameter2"] + 
      Data["weight_factors"]["parameter3"] 

Currently, in order to avoid entering Data["weight_factors"] repeatedly, I use the following commands:

d = Data["weight_factors"]
d["parameter1"] + d["parameter2"] + d["parameter3"]

But, I guess there should be an operator that does the same thing, without storing Data["weight_factors"] as an intermediate variable. I was wondering if such a command or an operator exists.

Data["weight_factors"]<unknown operator>(["parameter1"] + 
                                         ["parameter2"] +
                                          ... 
                                         ["parametern"])<unknown operator>

EDIT: In the example given above, it was just a sum operation. But it could for example be:

Data["weight_factors"]["parameter1"] * Data["weight_factors"]["parameter2"] + Data[‌​"weight_factors"]["parameter3"]

But I do not want enter Data["weight_factors"] repeatedly. That's the thing I am searching for... I don't know whether such an operator exists. (In MATLAB, there exists such a thing for cell structures).

T-800
  • 1,543
  • 2
  • 17
  • 26
  • I found the answer of @iCodez better; I don't have to import a module... I will probably implement by using `'.itervalues()'`. – T-800 May 23 '14 at 22:33
  • Oh, so you're just asking how do you get the values from a dict? Someone might flag this as a repeat question... – Russia Must Remove Putin May 23 '14 at 22:36
  • possible duplicate of [PYTHON how to extract all of the values from a dictionary](http://stackoverflow.com/questions/7002429/python-how-to-extract-all-of-the-values-from-a-dictionary) – Russia Must Remove Putin May 23 '14 at 22:39
  • As I have written in my question, I'm searching for the `` but I couldn't find anything similar or relevant. Therefore, I needed to ask it as a new question. Even at giving a title to my question, I was unsure about how to state it (can be checked through my edit history)... – T-800 May 23 '14 at 22:41
  • @AaronHall, for example in the example given above, it was just a sum operation. But it could for example be: `Data["weight_factors"]["parameter1"]*Data["weight_factors"]["parameter2"]+Data["weight_factors"]["parameter3"]`. But I do not want enter `Data["weight_factors"]` repeatedly. That's the thing I am searching for. – T-800 May 23 '14 at 22:48
  • I'm thinking you should just continue to use assignment like you were doing then. And now you know how to access a dict values, which you could also assign to something. But the question itself is a duplicate as far as I can tell. If others agree, it will be closed. No big deal. – Russia Must Remove Putin May 23 '14 at 22:50
  • @AaronHall I haven't learned how to access the values of dict from that answer. But for my specific case, it remembered me that I could use it. I am just searching for an operator. But I don't know if such an operator even exists... – T-800 May 23 '14 at 22:53

3 Answers3

5

No, that kind of operator does not exist for the built-in dict type.

I suppose you could make your own dict type that inherited from dict and overloaded an operator:

class MyDict(dict):
    def __add__(self, other):
        """Overload the + operator."""
...

but that is somewhat inefficient and not very good for readability.

If you just want to sum the values, you can use sum and dict.values (dict.itervalues if you are using Python 2.x):

>>> Data = {
... "weight_factors" : {
...     "parameter1" : 10,
...     "parameter2" : 30,
...     "parameter3" : 30
...     },
... "other_info" : {
...     }
... }
>>> sum(Data["weight_factors"].values())
70
>>>

Otherwise, I would just use what you have now:

d = Data["weight_factors"]
myvar = d["parameter1"] * d["parameter2"] + d["parameter3"]

It is about as clean and efficient as you can get.

  • Right, I could use sum() and .values(). Thanks for your response. But I am actually searching for a general solution. If none exists, I would definitely use your suggestion! – T-800 May 23 '14 at 22:25
  • I think you're going to need to be more specific about what kind of "general solution" you're after; iCodez's answer exactly addresses the question I thought you were asking, anyway. – DSM May 23 '14 at 22:27
  • @DSM I am actually searching for an 'unknown operator', which I have stated in my question. But I don't know whether such an operator exists... – T-800 May 23 '14 at 22:44
  • @iCodez I guess that's the true answer of my question, or more precisely: the answer I was searching for. I don't know whether accepting your reply leads to misunderstanding of some aggressive users and some other readers. Maybe you have to edit your reply a little bit ;) – T-800 May 23 '14 at 23:43
  • 1
    @T-1000 - I'll incorporate my comment into my answer then. :) –  May 23 '14 at 23:47
0

For a general solution to repeatedly get the same item from a mapping or index, I suggest the operator module's itemgetter:

>>> import operator

>>> Data = {
    "weight_factors" : {
        "parameter1" : 10,
        "parameter2" : 30,
        "parameter3" : 30
        },
    "other_info" : {
        }
    }

Now create our easy getter:

>>> get = operator.itemgetter('weight_factors')

And call it on the object whenever you want your sub-dict:

>>> get(Data)['parameter1']

returns:

10

and

>>> sum(get(Data).values())

returns

70
Russia Must Remove Putin
  • 374,368
  • 89
  • 403
  • 331
0

If this is just "how do I access a dict's values easily and repeatedly?" you should just assign them like this, and you can reuse them again and again.

In Python 2:

vals = Data['weight_factors'].values() 

In Python 3, values returns an iterator, which you can't reuse, so materialize it in a list:

vals = list(Data['weight_factors'].values()) 

and then you can do whatever you want with it:

sum(vals)
max(vals)
min(vals)

etc...

Russia Must Remove Putin
  • 374,368
  • 89
  • 403
  • 331