Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unpack key,value pairs in python? [duplicate]

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.

like image 789
Feraru Silviu Marian Avatar asked Dec 18 '17 16:12

Feraru Silviu Marian


1 Answers

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

like image 56
mikeb Avatar answered Oct 03 '22 00:10

mikeb