Python - Dictionary views and sets

Introduction

Unlike Python 2.X's list results, Python 3.X's view objects returned by the keys method are set-like.

The returned values support common set operations such as intersection and union.

Demo

D = {'a': 1, 'b': 2, 'c': 3} 
print( D )# from   ww  w.  jav  a  2  s  . co  m

K = D.keys() 
V = D.values() 
print( K, V )

print( K | {'x': 4} )                   # Keys (and some items) views are set-like

Result

In set operations, views may be mixed with other views, sets, and dictionaries.

Demo

D = {'a': 1, 'b': 2, 'c': 3} 
print( D.keys() & D.keys() )            # Intersect keys views 
print( D.keys() & {'b'} )               # Intersect keys and set 
print( D.keys() & {'b': 1} )            # Intersect keys and dict 
print( D.keys() | {'b', 'c', 'd'} )     # Union keys and set
# from   w  w w.  j a  va  2  s.c  o  m

Result

Items views are set-like if they contain only immutable objects:

Demo

D = {'a': 1} 
print( list(D.items()) )                # Items set-like if hashable 
print( D.items() | D.keys() )           # Union view and view 
print( D.items() | D )                  # dict treated same as its keys 
# www.j a  v a  2s. co m
print( D.items() | {('c', 3), ('d', 4)} )           # Set of key/value pairs 
print( dict(D.items() | {('c', 3), ('d', 4)}) )     # dict accepts iterable sets too

Result

Related Topic