Search code examples
pythonargumentsattributeerror

Can't iterate over a python dictionary


I try to pass a dictionnary to a function that will "parse" it but I can't iterate over it, It looks simple but can't understand what's happening.

My function:

    def _build_options(self, options):
        print options
        for option, value in options.iteritems():
            if option not in self._optionslist:
                del options[option]
        return options

options:

 {'segment_container': None, 'use_slo': False, 'log_level': 'INFO', 
'dir_marker': 'False', 'changed': None, 'leave_segments': False, 'fail_fast':
 False, 'headers': 'X-Delete-After:50, X-Upload:None', 'meta': [], 
'ttl': None, 'segment_size': None, 'skip_identical': False}

My code raises this:

AttributeError: Values instance has no attribute 'iteritems'

Thanks

edit: type(options):

 <type 'instance'>

dir(options):

['__cmp__', '__doc__', '__init__', '__module__', '__repr__', '__str__',
 '_update', '_update_careful', '_update_loose', 'changed', 'dir_marker',
'ensure_value', 'fail_fast', 'headers', 'leave_segments', 'log_level', 'meta', 'read_file', 'read_module', 
'segment_container', 'segment_size', 'skip_identical', 'ttl', 'use_slo']

I tried options = dict(options) but I get the error:

    TypeError: iteration over non-sequence

Edit2: I have a method upload() in which I call _build_options():

def upload(self, paths, ttl, options):
     # [...]
     # print options, type(options)
     # the dictionnary is well printed but its type is "instance"
     opts = self._build_options(options)

upload() is called in an other file like this:

self.swift_mng.upload(filename, None, options)

and I get options from optparse.parse_args()


Solution

  • First of all, you are not using a dictionary, it just looks like that when you print it (it is the __str__ method in the class making it look like that).

    Read the documentation for optparse, and also this.

    options is an object containing values for your options. So far as I can tell, you cannot iterate over the options (there is no __iter__, for example, in the class), you can only test the individual option values.

    EDIT: However, I did find this that might be useful: http://code.activestate.com/lists/python-list/344094/