Prutser Prutser - 1 year ago 85
Python Question

Python: Using the list length to increment the index of the enumerated dictionary

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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download