Reputation: 11226
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
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
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
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
Reputation: 6583
Sure, just use:
for key,value in {'one':1, 'two':2, 'three':3}.items():
print key, ":", value
Upvotes: 2
Reputation: 34253
You could do:
for (key, value) in {'one':1, 'two':2, 'three':3}.items():
print key, value
Upvotes: 3