Saturday, August 1, 2015
python: dictionary (1)
Abstract: loop dictionary
The script:
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 1 17:10:03 2015
@author: yuan
"""
d={'g':3, 'a':12,'b':2,'c':32,'d':120,'e':102,'f':112}
print 'method 1:'
for key in d:
print key, d[key]
#faster than the method 1
print '\nmethod 2:'
for key in d.keys():
print key, d[key]
print '\nmethod 3:both key and value'
for key,value in d.iteritems():
print key, value
print '\nsorted loop:'
for key in sorted(d.keys()):
print key, d[key]
#transpose dictionary: key to value, value to key
dd=dict(zip(d.values(),d.keys()))
print dd
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment