Search code examples
pythondictionaryobjectkey-valuekeyvaluepair

How to unpack key,value pairs in python?


I'm trying to explore the Algorithmia image taggers in python.

client.algo("deeplearning/IllustrationTagger/0.2.5")
client.algo("deeplearning/InceptionNet/1.0.3")

But that's not quite relevant to this question, as it applies to dictionaries in general.

for dict in dictList:
    print(dict)

And this is the output:

//{'safe': 0.9950032234191896}

//{'questionable': 0.004409242421388626}

//{'explicit': 0.00011681715113809332}

I can access the key just fine:

for dict in dictList:
    for key in dict:
        print(key)

//safe

//questionable

//explicit

But when I'm trying to unpack both the key and the value:

for dict in dictList:
    for key, value in dict:
        print(key)
        print(value)

I get this error:

for key, value in dict:
ValueError: too many values to unpack (expected 2)

How can I access both the key and the value ?

EDIT: I've renamed obj and array to dict and list not to confuse with Javascript notation.


Solution

  • Like this - first:

    for obj in objArray:
        for key in obj:
            value = obj[key]
            print(key)
            print(value)
    

    Second (python 3):

    for obj in objArray:
        for key, value in obj.items():
               print(key)
               print(value)
    

    For python 2 you can use for key, value in d.iteritems()