Say, I have a dic like this
my_dictionary = {'a':1,'c':5,'b':20,'d':7}
Now, I want to do this with my dic:
if my_dictionary['a'] == 1 and my_dictionary['d'] == 7:
print my_dictionary['c']
This looks ridiculous because I am typing my_dictionary 3 times!
So is there any syntax which would allow me to do something like this:
within my_dictionary:
if a == 1 and d == 7:
print c
This would actually work if I didn't have anything more (in this case b) in my dic:
def f(a,d,c):
if a == 1 and d == 7:
print c
f(**my_dictionary)
You can change your function to
def f(a,d,c,**args):
if a == 1 and d == 7:
print c
then it will work even if you have other items in the dict.
You can use operator.itemgetter to minimize multiple indexing :
>>> if operator.itemgetter('a','d')(my_dictionary)==(1,7):
... print operator.itemgetter('c')(my_dictionary)
And you can use it in a function :
>>> def get_item(*args):
... return operator.itemgetter(*args)(my_dictionary)
...
>>>
>>> if get_item('a','d')==(1,7):
... print get_item('c')
...
5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With