'ValuesViewHDF5' object is not subscriptable - python

I have tried many solutions but can't seem to solve the problem. This code is in Python 2.7 and I am using Python 3.7. While searching I find out that this gives an error in Python 3.7. Can anyone help me how to remove this error in Python 3.7?
print('Loading c3d features ...')
features = h5py.File(self._options['feature_data_path'], 'r')
self._feature_ids = features.keys()
self._features = {video_id:np.asarray(features[video_id].values()
[0]) for video_id in self._feature_ids}
This is the error I am getting:
E:\jupyter book\data_provider.py in <dictcomp>(.0)
---> 68 self._features
{video_id:np.asarray(features[video_id].values()[0]) for
video_id in self._feature_ids}
69
70
TypeError: 'ValuesViewHDF5' object is not subscriptable

Try moving the subscript [0] outside the np.asarray() bit:
self._features = {video_id:np.asarray(features[video_id].values())[0]
for video_id in self._feature_ids}
Or converting the group.values() object to a list:
self._features = {video_id:np.asarray(list(features[video_id].values())[0])
for video_id in self._feature_ids}
Calling features[video_id].values() with Py2 returns a list; on Py3, it returns a set-like object (http://docs.h5py.org/en/stable/high/group.html#Group.values). This means the group.values() object is no longer directly subscriptable in Py3. You'll need to convert it to a list or array-like object first via list(group.values()) or np.asarray(group.values()). The same applies to group.keys() etc.

Related

'tuple' object does not support item assignment in torch.cat()

I am trying to use the torch.cat() to contenate the torch tensor. However, I face the error messagge with --> 'tuple' object does not support item assignment.
Here are my code:
inputs = tokenizer.encode_plus(txt, add_special_tokens=False, return_tensors="pt")
input_id_chunks = inputs["input_ids"][0].split(510)
mask_chunks = inputs["attention_mask"][0].split(510)
print(type(input_id_chunks))
for i in range(len(input_id_chunks)):
print(type(input_id_chunks[i]))
print(input_id_chunks[i])
input_id_chunks[i] = torch.cat([
torch.Tensor([101]), input_id_chunks[i], torch.Tensor([102])
])
The outputs looks fine, the inputs_id_chunks[i] is torch.Tensor:
`<class 'tuple'>
<class 'torch.Tensor'>`
But I got the following print and error message:
TypeError: 'tuple' object does not support item assignment
in torch.cat()
I have using the small testing code for torch.cat() and it works fine, but I don't know what is missing in my original codes.
you can't change tuple value, instead you can assign it to list, then append new value to it and then after all changes you want to implement, you should assign again it to tuple.
please check this link

cannot pickle 'generator' object created using yield key-word

As shown in the below posted code, I call __yieldIterables() to generate iterables according to what the list self.__itersList contains. At run time I receive the following error:
TypeError: cannot pickle 'generator' object
Please let me know how to correct the below code in such a way that I can still convert the contents of self.__itersList to iterables that can be passed to the self.run()
code:
def postTask(self):
arg0 = self.getDistancesModel().getFieldCoordinatesAsTextInWKTEPSG25832()
self.__itersList.append(self.getDistancesModel().getNZCCCenterPointsAsString())
self.__itersList.append(self.getDistancesModel().getZCCCenterPointsAsString())
self.__itersList.append(self.getDistancesModel().getNoDataCCenterPointsAsString())
with Pool(processes=self.__processesCount,initializer=self.initPool,initargs=(arg0,)) as DistancesRecordsPool.pool:
self.__iterables = self.__yieldIterables()
self.__chunkSize = PoolUtils.getChunkSizeForLenOfIterables(lenOfIterablesList=len(self.__itersList),cpuCount=self.__cpuCount)
for res in DistancesRecordsPool.pool.map(func=self.run,iterable=self.__iterables,chunksize=self.__chunkSize):
self.__res.append(res)
DistancesRecordsPool.pool.join()
gPostgreSQLHelperObject.closeConnection()
return self.__res
def __yieldIterables(self):
for i in self.__itersList:
yield i

Python Conversion of Generic list to List[str] (Python 2.7)

I am facing an issue with my code. Where I need to extract a list of strings from dictionary (returned by method 1) and pass it as parameter to method 2.
viewerIDs = Parent.GetViewerList()
if (len(viewerIDs) <= 0):
return
viewerIDsNames = Parent.GetDisplayNames(viewerIDs)
viewerNames = []
for key in viewerIDsNames:
viewerNames.append(str(viewerIDsNames[key]))
#Get their ranks
viewerRanks = Parent.GetRanksAll (viewerNames)
I get the below error in the last line
Expected List[str], got list
I have tried the below methods, to set viewerNames and i am facing the same error
#viewerNames = viewerIDsNames.items()
#viewerNames = list(viewerIDsNames.values())
#viewerNames = map(str,viewerIDsNames.values())
#viewerNames = [str(name) for name in viewerIDsNames]
Can anyone please point out how I can cast this properly.
Regards,
Joshua.
I suspect you're getting this answer from a linter rather than from Python itself. You need to tell the linter that viewerNames is List[str]
viewerNames = [] # type: List[str]
Some linters try to figure out the type of a variable from the very first time it is assigned, and never look any further. When you assign [] to viewerName, the linter knows that it is a list, but has no idea what's inside the list.

Attribute Error: list object has no attribute 'apply'

time_weight = list(100*np.exp(np.linspace(-1/divisor, -(num_steps-1)/divisor, num_steps))).apply(lambda x:int(x))
When I try this, I get the following error in Python 3.7.
AttributeError: 'list' object has no attribute 'apply'
Can anyone help with this?
As the error said, list type has no apply attribute.
This said, if you have a list l and you want to set to int type every element in it you may use:
l = [int(x) for x in l]
or
l = list(map(int,l))
As the error suggests, list has no apply method. If what you want to do is convert every element to an int, you could remove the lambda function and instead use astype(int):
time_weight = list((100*np.exp(np.linspace(-1/divisor, -(num_steps-1)/divisor, num_steps))).astype(int))

Getting 'dict_keys' object does not support indexing despite casting to list

I am using Python 3 and despite of casting to list, I cannot seem to run my program.
This is the function calling:
path = euleriancycle(edges)
And this is where I have used the keys method:
def euleriancycle(e):
currentnode = list[e.keys()[0]]
path = [currentnode]
I tried to run it without type-casting to list and got this error. After rummaging about this site and similar queries, I followed the solutions suggested and type-cast to list but to no avail. I got the same error.
This is the error track:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-56-356b905111a9> in <module>()
45 edges[int(edge[0])] = [int(edge[1])]
46
---> 47 path = euleriancycle(edges)
48 print(path)
<ipython-input-56-356b905111a9> in euleriancycle(e)
1 def euleriancycle(e):
----> 2 currentnode = list[e.keys()[0]]
3 path = [currentnode]
4
5 while true:
TypeError: 'dict_keys' object does not support indexing
The dict_keys objects, like sets, can not be indexed.
Instead of this:
list[e.keys()[0]]
The next closest thing would be this:
list(e)[0]
Python makes no guarantee on what key from the dict will be returned, so you might want to put an ordering on it yourself.
You are trying to index the dict_keys object, then convert that element to a list (syntax error of list[...] vs list(...) aside). You need to convert the entire object to a list first, then index it.
currentnode = list[e.keys()[0]] # Wrong
currentnode = list(e.keys()[0]) # Less wrong, but still wrong
currentnode = list(e.keys())[0] # Right
list takes any iterable, and the iterator returned by a dictionary is just an iterator over its keys, so you don't need to call keys explicitly.
currentnode = list(e)[0]

Categories