John Eipe
John Eipe

Reputation: 11226

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

Upvotes: 2

Views: 2393

Answers (5)

wdh
wdh

Reputation: 1672

You can use the iteritems method to iterate through the dict

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

Upvotes: 0

Danilo Bargen
Danilo Bargen

Reputation: 19462

To iterate over key/value pairs, you can use .items() or .iteritems():

for k, v in {'one':1, 'two':2, 'three':3}.iteritems():
    print '%s:%s' % (k, v)

See http://docs.python.org/library/stdtypes.html#dict.iteritems

Upvotes: 3

Rob Cowie
Rob Cowie

Reputation: 22619

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

Upvotes: 5

Piotr Sobczyk
Piotr Sobczyk

Reputation: 6583

Sure, just use:

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

Upvotes: 2

Thomas Zoechling
Thomas Zoechling

Reputation: 34253

You could do:

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

Upvotes: 3

Related Questions