Search code examples
pythondictionaryiterable-unpacking

unpacking dictionary in python and getting values


I have this dictionary and I am trying to extract the values

dict = {'distances': array([ 870.99793539]), 'labels': array([2])}

I tried to use

self.printit(**dict)

def printit(distances,labels):         
    print distances
    print labels

but I am getting error

TypeError: printit() got multiple values for keyword argument 'distances'

Solution

  • Why you were getting a TypeError:

    When you call a method with self.printit(**somedict), the first argument passed to the function printit is self. So if you define

    def printit(distances, labels):
    

    the distances is set to self. Since somedict contains a key called distances, the distances keyword is being supplied twice. That's the why the TypeError was being raised.


    How to fix it:

    Your function

    def printit(distances,lables):  
    

    uses a variable named lables, but the dict has a key spelled labels. You probably want to change lables to labels.


    Add self as the first argument to printit.

    def printit(self, distances, labels): 
    

    Calling the first argument self is just a convention -- you could call it something else (though that is not recommended) -- but you definitely do need to put some variable name there since calling

    self.printit(...) will call printit(self, ...).


    For example,

    import numpy as np
    class Foo(object):
        def printit(self, distances, labels): 
                print distances
                print labels
    
    somedict = {'distances': np.array([ 870.99793539]), 'labels': np.array([2])}
    self = Foo()
    self.printit(**somedict)
    

    prints

    [ 870.99793539]
    [2]