geoJshaun
geoJshaun

Reputation: 709

TypeError: object has no attribute '__getItem__'

I've looked at another post with this heading but I'm puzzled because my values are already integers. I want the script to look at each key's values (an array with multiple values), sort the array by making it a list, and then iterate through the sorted and converted list's values subtracting the first from the second, then the second from the third, and so on, storing the differences in a list.

b = {"a":[5,2,1],"b":[8,4,3]}

for k in b.values():
    eVals = []
    #print listVals
    x = 0
    for i in sorted(k):
        dif = i[x+1] - i[x]
        print dif
        eVals.append(dif)
        x +=1

Here is the error:

Traceback (most recent call last):
  File "C:\Python27\ArcGIS10.2\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 323, in RunScript
    debugger.run(codeObject, __main__.__dict__, start_stepping=0)
  File "C:\Python27\ArcGIS10.2\Lib\site-packages\pythonwin\pywin\debugger\__init__.py", line 60, in run
    _GetCurrentDebugger().run(cmd, globals,locals, start_stepping)
  File "C:\Python27\ArcGIS10.2\Lib\site-packages\pythonwin\pywin\debugger\debugger.py", line 654, in run
    exec cmd in globals, locals
  File "N:\Python\test_dict.py", line 1, in <module>
    b = {"a":[5,2,1],"b":[8,4,3]}
TypeError: 'int' object has no attribute '__getitem__'

Upvotes: 2

Views: 2738

Answers (2)

ppasler
ppasler

Reputation: 3729

You try to use __getitem__ on an int.

Here's a possible solution

inp  = {"a":[5,2,1],"b":[8,4,3]}

out = {}
for key, lis in inp.iteritems():
    difLis = []
    sLis = sorted(lis)
    for i, _ in enumerate(sLis[:-1]):
        dif = sLis[i+1] - sLis[i]
        print "%d - %d = %d" % (sLis[i+1], sLis[i], dif)
        difLis.append(dif)
    out[key] = difLis
print out # {'a': [1, 3], 'b': [1, 4]}

Upvotes: -1

wim
wim

Reputation: 363173

>>> b = {"a":[5,2,1],"b":[8,4,3]}
>>> for key, value in b.iteritems():
...     value.sort()
...     value[:] = [cur-prev for cur, prev in zip(value, [0] + value[:-1])] 
...     
>>> b
{'a': [1, 1, 3], 'b': [3, 1, 4]}

If you have numpy conveniently available, you can do this in a one-liner comprehension:

>>> import numpy as np
>>> b = {"a":[5,2,1],"b":[8,4,3]}
>>> {k: np.diff([0] + sorted(v)) for k, v in b.iteritems()}
{'a': array([1, 1, 3]), 'b': array([3, 1, 4])}

Upvotes: 2

Related Questions