0

I am looping and enumerating a dictionary as following:

for column, key, in enumerate(guid_material_dictionary.iteritems()):
            print column, key, len(key[1])

It gives the following output:

0 ('0GVHv3rDXBewxnxizHODe9', ['Steen', 'Isolatie', 'Spouw']) 3
1 ('2kj3p602r8MgLr9ocS99Pp', ['Beton C']) 1
2 ('3_gGbJ1L17UP8z1VVIOPak', ['Beton', 'Pleister', 'Baksteen', 'Folie']) 4
3 ('3mROnO4_7VbAI2oRYB55vS', ['Koper']) 1
4 ('1HX$_kbR1AKxF1CmKGciQa', ['Steen - kalkzandsteen']) 1
5 ('0xtMj9XwvBjvPzzyvlFeQ0', ['Isolatie - Steenwol zacht']) 1

The list lengths vary a lot in the output. What I am trying to do is to use the list length to increment the column count. So that the column count is defined by the lengths of the list. This output is an example of what I intent to do.

0 ('0GVHv3rDXBewxnxizHODe9', ['Steen', 'Isolatie', 'Spouw']) 3
3 ('2kj3p602r8MgLr9ocS99Pp', ['Beton C']) 1
4 ('3_gGbJ1L17UP8z1VVIOPak', ['Beton', 'Pleister', 'Baksteen', 'Folie']) 4
8 ('3mROnO4_7VbAI2oRYB55vS', ['Koper']) 1
9 ('1HX$_kbR1AKxF1CmKGciQa', ['Steen - kalkzandsteen']) 1
10 ('0xtMj9XwvBjvPzzyvlFeQ0', ['Isolatie - Steenwol zacht']) 1

I hope the question is clear. What I tried is to add the colum integers with the list length but it does not work because the column needs to be defined by the list lengths.

Claus
  • 119
  • 1
  • 12

2 Answers2

0

You can't use enumerate for that. But it is easy enough to write your own generator:

def my_enumerate(iterable):
    total = 0
    for key, value in iterable:
        yield total, (key, value)
        total += len(value)

So you can use it like this:

for column, key in my_enumerate(guid_material_dictionary.iteritems()):
    print column, key, len(key[1])
Bakuriu
  • 98,325
  • 22
  • 197
  • 231
0

Just skip the enumerate part and use a variable:

column = 0
for key in guid_material_dictionary.iteritems():
    print column, key, len(key[1])
    column += len(key[1])

Note that you increase the column variable after using it.


Note that the order of dictionary keys is arbitrary, so you can't really match the column variable with the keys.

DerWeh
  • 1,721
  • 1
  • 15
  • 26