Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When defining a Python dictionary, how can I use values of given fields to calculate an other field?

Consider the code

a = 2
b = 3
mylist = {'a' : a, 'b' : b, 'product' : a * b}

This produces a dictionary of three fields, of which the third is calculated using the values of the first and second. I am looking for a more compact definition of mylist. I have tried (1)

mylist = {'a' : 2, 'b' : 3, 'product' : a * b}

which gives the error

NameError: name 'a' is not defined

and (2)

mylist = {'a' : 2, 'b' : 3, 'product' : mylist['a'] * mylist['b']}

which gives the error

NameError: name 'mylist' is not defined

I would like to find a shorter command of the form (1) because you do not need to need to mention the name of the dictionary. Maybe there exists something like currentdictionary['a']?

like image 368
Karlo Avatar asked Jan 20 '26 03:01

Karlo


2 Answers

I'd use something like a computed property in this case. It'll lazily evaluate the property when you need it; at call time. Much more robust than actively managing the product as a key-value pair.

class Pair(object):
    def __init__(self, a, b):
        self.a = a
        self.b = b

    @property
    def product(self):
        return self.a * self.b

Sample Output:

>>> Pair(2, 3).product
6

Using a dictionary here is possible but strikes me as a shoehorned solution, (1) you'd need to contend with checking if key(s) exist on lookup and (2) also maintaining a synchronized product should a or b change.

like image 198
ospahiu Avatar answered Jan 21 '26 16:01

ospahiu


You could use a function to specify the desired keys of the dictionary and use inspect to view the signature at run time:

import inspect
a = 2
b = 3
def get_list(a, b, product):
   pass

mylist = inspect.getcallargs(get_list, a, b, a*b)

Output:

{'a': 2, 'product': 6, 'b': 3}

The benefit of using a function in this case is that you can built a solution to find mylist around other potential objects in your code.

like image 26
Ajax1234 Avatar answered Jan 21 '26 15:01

Ajax1234



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!