0

I'm trying to create the following data structure on the fly by reading the output of another script line by line, if certain combinations of thresholds are breached, I want to track those in a dictionary:

data = {}

data[device]['mntpt']   = mntpt
data[device][timestamp] = { 'r_ops': r_ops, 'r_avgrtt': r_avgrtt, 'r_avgexe': r_avgexe, 'w_ops': w_ops, 'w_avgrtt': w_avgrtt, 'w_avgexe': w_avgexe }

For each device, there can be a varying number of timestamps, each containing 6 datapoints. The r_xxx and w_xxx variables are floats. device, mntpt and timestamp are strings.

I'm getting the following error:

TypeError: unsubscriptable object

I get the same error if I comment out this line:

# data[device]['mntpt']   = mntpt

What am I doing wrong here?

Thx

nucsit026
  • 572
  • 4
  • 13
Rhugga
  • 35
  • 1
  • 4
  • What is the value at the key ``device``? If it's not a dict, what you're trying to do won't work. You should probably look into the [``deafultdict``](https://docs.python.org/2/library/collections.html#defaultdict-objects) class. – aruisdante May 31 '14 at 02:16

2 Answers2

1

genisage has a working solution. You can also use a defaultdict

from collections import defaultdict

data = defaultdict(dict)

data[device]['mntpt']   = mntpt
data[device][timestamp] = { 'r_ops': r_ops, 'r_avgrtt': r_avgrtt, 'r_avgexe': r_avgexe, 'w_ops': w_ops, 'w_avgrtt': w_avgrtt, 'w_avgexe': w_avgexe }

The way this works is that if you try to assign to data[device], but there's no dictionary defined there yet, it will automatically create one for you.

This also works with list, int etc. Here's a list example:

from collections import defaultdict

data = defaultdict(list)

data[device].append(mntpt)
data[device].append({ 'r_ops': r_ops, 'r_avgrtt': r_avgrtt, 'r_avgexe': r_avgexe, 'w_ops': w_ops, 'w_avgrtt': w_avgrtt, 'w_avgexe': w_avgexe })

EDIT: This solution only works in Python 2.5 or newer.

Martin Konecny
  • 50,691
  • 18
  • 119
  • 145
0

When you say data = {} and then data[x][y] = z, python is yelling at you because you haven't told it what data[x] is yet, so it doesn't know how to subscript it with y

You should say:

data = {}
data[device] = {}
data[device]['mntpnt'] = mntpnt
data[device][timestamp] = {stuff}

Then you've let python know in advance that it's an empty dict, and it knows how to subscript a dict.

genisage
  • 1,089
  • 7
  • 15
  • Awesome thx... been writing perl for so long, it actually lets you do sloppy stuff like that. =) – Rhugga May 31 '14 at 02:28