Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Temporarily unpack dictionary

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)
like image 555
Pekka Avatar asked Jan 27 '26 12:01

Pekka


2 Answers

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.

like image 188
yangjie Avatar answered Jan 30 '26 02:01

yangjie


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
like image 36
Mazdak Avatar answered Jan 30 '26 00:01

Mazdak



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!