Creating a list with holes

Larry Martell larry.martell at gmail.com
Fri Jan 3 10:55:58 EST 2014


On Fri, Jan 3, 2014 at 10:37 AM, Chris Angelico <rosuav at gmail.com> wrote:
> On Sat, Jan 4, 2014 at 2:19 AM, Larry Martell <larry.martell at gmail.com> wrote:
>> I think I know the answer is no, but is there any package that allows
>> creating a list with holes in it? E.g. I'd want to do something like:
>>
>> x[10] = 12
>> x[20] = 30
>>
>> I'm thinking of something like defaultdict but for lists (I know
>> that's very different, but ... )
>
> Depending on what exactly you need, it's probably worth just using a
> dict. In what ways do you need it to function as a list? You can
> always iterate over sorted(some_dict.keys()) if you need to run
> through them in order.
>
> Alternatively, if you expect to fill in most of the elements, it's
> possible you'd be happier working with a subclass of list that
> auto-expands by filling in the spare space with a singleton meaning
> "no element here". The code probably exists somewhere, but if not, it
> wouldn't be hard to write. Then it'd be a list, but you can start with
> it empty and assign as you describe above.
>
> What's the use case? I expect that one or the other of those options
> would cover most cases, but maybe yours is different.

Yeah, googled and didn't find anything, then started writing it myself
last night, then this morning decided to ask if it already existed.

The use case is that I'm parsing a XML file like this:

          <Parameter Name="DefaultVersion">
            <Values>
              <Value>
                <Default>True</Default>
              </Value>
            </Values>
            <Values>
              <Value>
                <Current>False</Current>
              </Value>
            </Values>
            <Values>
              <Value>
                <Default>True</Default>
                <Current>False</Current>
              </Value>
            </Values>
            <Values>
              <Default>True</Default>
            </Values>

This is an existing program that is putting the data into a dict. The
dict keys are ['DefaultVersion','Default'] and
['DefaultVersion','Current']. These contain lists that have the
True/False values. It's currently not correctly handling the missing
items so it ends up with:

['DefaultVersion','Default'][0] = True
['DefaultVersion','Default'][1] = True
['DefaultVersion','Current'][0] = False

When it should be:

['DefaultVersion','Default'][0] = True
['DefaultVersion','Default'][1] = None
['DefaultVersion','Current'][0] = None

And so on.

This dict/list is then processed by other existing code, so I don't
want to have to rewrite a ton of code - I just want to fix the list so
the items end up in their correct slots.



More information about the Python-list mailing list