john pfeiffer
  • Home
  • Categories
  • Tags
  • Archives

dictionary iteration iteritems viewkeys

new_empty = {}
new_empty_same = dict()

b = 'b'
mylist = [ 1, 2 ]
stuff = { 'key': 'value' , 'bkey': b , 'ckey': mylist }
stuff_same = dict( [ ('key', 'value') , ('bkey', b) , ('ckey', mylist) ] )
stuff_same_again = dict( key='value', bkey=b, ckey=mylist )     # useful when the key is a string

len( stuff ) == len( stuff_same ) == len( stuff_same_again )
stuff == stuff_same == stuff_same_again

print stuff[ 'bkey' ]
'bkey' in stuff     # True
print stuff.get( 'bkey' )   # b

del stuff[ 'bkey' ]
'bkey' in stuff     # False
print stuff.get( 'bkey' )   # None

stuff.clear()
popped_value = stuff_same.pop( 'bkey' )
try:
    stuff_same.pop( 'bkey' )    # raises KeyError
except KeyError:
    pass

arbitrary_key_value_tuple = stuff_same.popitem()    # useful for destructive iteration

stuff.update( ckey = mylist )
stuff.clear()
stuff.update( stuff_same_again )    #

print stuff.keys()  # ['ckey', 'key']  (whole list at once)
print iter( stuff ) # <dictionary-keyiterator object at 0x0000000002215908>
for key in stuff.iterkeys():        # iterators are lazy rather than generating the whole list at once
    print key
for value in stuff.itervalues():
    print value
print stuff.values()  # [ [1,2] , 'value' ]

print stuff.items() # [ ('ckey', [1,2]) , ('key','value') ]
for k,v in stuff.iteritems():
    print k,v




dictionary_comprehension = { x: x**2 for x in (2, 4, 6) }

# variations on creating or iterating over dictionaries and sequences
# d = {key: value for (key, value) in sequence}

dictionary.setdefault( 'key' , 'defaultvalue' ) # sets a default to return if the key is not in the dict()

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Views dynamically display a dictionary's entries (i.e. readonly access)
example = dict( a='1', b='2', c='3' )
example_viewkeys = example.viewkeys()
example_viewvalues = example.viewvalues()
example_viewitems = example.viewitems()

'1' in example_viewvalues       # True

print len( example_viewkeys )   # 3
example.popitem()
print len( example_viewkeys )   # 2

# if iterating many times over a changing dictionary, don't rebuild the generator or list each time...
for key in iter( example_viewkeys ):
    print key

new_intersection_set = example_viewkeys & other_example
new_union_set = example_viewkeys | other_example
new_difference_set = example_viewkeys - other_example               # example_viewkeys without anything in other
new_symmetric_difference_set = example_viewkeys ^ other_example     # set of not common elements


- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
LOOPING
for i, v in enumerate( ['tic', 'tac', 'toe'] ):     # enumerate over a sequence
    print i, v

# viewitems()

  • « oxygen skip decorator
  • google bigquery »

Published

Apr 16, 2013

Category

python

~280 words

Tags

  • dictionary 4
  • iteration 1
  • iteritems 1
  • python 180
  • viewkeys 1