Python - Dictionary views and list

Introduction

The following code uses the list built-in to work with list keys, values and pairs.

Demo

D = dict(a=1, b=2, c=3) 
print( D )#  ww  w.j  a v a2  s .  c  o m

K = D.keys()                   # Makes a view object in 3.X, not a list 
print( K )
print( list(K) )                        # Force a real list in 3.X if needed 

V = D.values()                 # Ditto for values and items views 
print( V )
print( list(V) )

print( D.items() )
print( list(D.items()) )

#print( K[0] )  # List operations fail unless converted 
print( list(K)[0] )

D = dict(a=1, b=2, c=3) 
for k in D.keys(): print(k)    # Iterators used automatically in loops 

D = dict(a=1, b=2, c=3) 
for key in D: print(key)       # Still no need to call keys() to iterate

Result

Dictionary views in 3.X dynamically reflect future changes made to the dictionary after the view object has been created:

Demo

D = {'a': 1, 'b': 2, 'c': 3} 
print( D )#  www .  j a v  a  2 s .co m

K = D.keys() 
V = D.values() 
print( list(K) )                        # Views maintain same order as dictionary 
print( list(V) )

del D['b']                     # Change the dictionary in place 
print( D )

print( list(K) )                        # Reflected in any current view objects 
print( list(V) )                        # Not true in 2.X! - lists detached from dict

Result

Related Topic