6

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.

Brian Tompsett - 汤莱恩
  • 5,438
  • 68
  • 55
  • 126

1 Answers1

9

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()

mikeb
  • 9,707
  • 4
  • 48
  • 104
  • This question has been answered many times, and your answer is the same as always, so it does not bring anything new: https://stackoverflow.com/questions/26660654/how-do-i-print-the-key-value-pairs-of-a-dictionary-in-python – eyllanesc Dec 18 '17 at 16:45