Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

looping a unnamed dictionary in python

Is there a way to print both key and value of a anonymous dict in python.

for key in {'one':1, 'two':2, 'three':3}:
    print key, ":", #value
like image 429
John Avatar asked Dec 20 '25 05:12

John


2 Answers

for key, value in {'one':1, 'two':2, 'three':3}.iteritems():
    print key, ":", value

By default, iterating over it returns its keys. .iteritems() returns 2-tuples of (key, value).

like image 50
Rob Cowie Avatar answered Dec 22 '25 17:12

Rob Cowie


You could do:

for  (key, value) in {'one':1, 'two':2, 'three':3}.items():
    print key, value
like image 43
Thomas Zoechling Avatar answered Dec 22 '25 18:12

Thomas Zoechling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!