Search code examples
pythondictionaryunpack

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)

Solution

  • 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.