List comprehension with single object in python - python

I have a list like so,
<Node: uuid=c1f462dde9ff6eb80b4197db5972c4feaf29e4e7, name=new-node, state=PENDING, public_ips=[], private_ips=['10.0.2.217'], provider=Amazon EC2 (ap-northeast-1) ...>
Node is a single object in the list, and I want to access only the name attribute from the object. I tried this,
[i.name for i in my_list]
It is showing error as:
Traceback (most recent call last):
File "create.py", line 50, in <module>
name = [i.name for i in sample]
TypeError: 'Node' object is not iterable
How to fetch only name attribute from this object?

The error is pretty self-explanatory, you are trying to iterate over something that is not iterable. i.e. you cannot loop over it.
You simply need to access it as sample.name

Related

Is it possible to get an error when accidentally assigned wrong type in python?

For example I have next code:
name = str('John Doe')
Let's imagine after I assign to name = 1, but code still valid.
Is it possible to get an error in this case in Python or within some special tool?
Python is dynamically typed, so you can assign pretty much anything to anything. This would work:
name = 1
name = "Bill"
You can add in type checking with mypy
I'm not sure if you are trying to raise an error, or just wondering if an error might arise if you change the value.
Raise an error
you could check the type using isinstance(obj, class) and raise TypeError(msg).
Is it possible to get an error?
Not directly, but you could as a consequence get an error if you use string operations/methods on an integer.
Example:
>>> name = "john doe"
>>> name = 1
>>> name.split(" ")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute 'split'

Python Iterating Through Dictionary With Tuples

I am designing a system that involves iterating through a pre-made non python standard dictionary with an iter function. I am trying to iterate through the tuples but keep getting this stupid Error. Also, this error only happens half the time, due to a bit flipping function that messes with inputs
TypeError: 'tuple' object cannot be interpreted as an integer
Probably an easy fix, can anyone spot?
Heres relevant code:
In my main program:
for tup in crusherdict.CrusherDict(db2, fields[0]):
log.write("VOTE\t{}\t{}\n".format(tup[0][0], tup[0][1]))
Place in Dictionary giving me the iter error:
def __iter__(self):
for i in range(self.__len__()):
yield self.db.fetch(entryName(self.name,i))
Heres db.fetch:
def fetch(self,key):
return self.cache[key]
And entryName:
def entryName(dict, str):
return (dict, "E", str)
Full BackTrace:
in <module>
if commands[line[0]](db, tempDict, logFile, line):
in cast
return inq(db, tempDict, logFile, ("INQ", tempDict["voterID"]))
line 100, in inq
for tup in crusherdict.CrusherDict(db3, fields[0]):
crusherdict.py", line 91, in __iter__
for i in range(self.__len__()):
TypeError: 'tuple' object cannot be interpreted as an integer
>>>
The traceback says the error happens at:
for i in range(self.__len__()):
We know that range expects an integer so this is hopeful, and indeed we can replicate the error message in Python 3:
>>> range((1,2))
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: 'tuple' object cannot be interpreted as an integer
Therefore __len__ is not returning an integer as it should.
Your function entryName() returns a tuple of three elements. This tuple is used by fetch as an index into your cache. Since we have to guess from the bits you provide, I'm guessing your cache is a plain list, and needs an integer index, not a tuple. (Also you're passing an int to an argument you named str, so you're definitely confused about something here.)

Why does the following attribute error occur?

I get the following error when trying to execute the following in Python with the PuLP library
for i in range(0, items):
print('x{0} = {1}'.format(i+1, value('x{0}'.format(i+1))))
That is my code which throws the following error
Traceback (most recent call last):
File "C:/Python34/knapsack.py", line 81, in <module>
print('x{0} = {1}'.format(i+1, value('x{0}'.format(i+1))))
File "C:\Python34\lib\site-packages\pulp-1.6.1-py3.4.egg\pulp\pulp.py", line 1990, in value
else: return x.value()
AttributeError: 'str' object has no attribute 'value'
My question is why does this not work. Splitting the print statement tends to work correctly.
The value method expects a PuLP variable object, not a string with the same name as one.
In order to evaluate your string back to a python variable, you need to eval it, so that would look like.
value(eval('x{0}'.format(i+1)))

AttributeError, why?

I'm writing a program that solves a tetravex and I encountered this error:
AttributeError: 'list' object has no attribute 'PlacementList'.
I tried everything I know but don't know why I'm getting that error. Could you please tell me what I did wrong?
This is a pastebin link to my code: http://pastebin.com/d1WdbCUu
It happens when you are trying to get PlacementList attribute of a list, obviously.
Here is the example:
>>> a = []
>>> a.PlacementList
Traceback (most recent call last):
File "<pyshell#49>", line 1, in <module>
a.PlacementList
AttributeError: 'list' object has no attribute 'PlacementList'
Just find the code where something similar happens - you are trying to get PlacementList attribute of the object that can be of type list.

TypeError: list objects are unhashable

totalCost = problem.getCostOfActions(self.actions)
Looks like you are trying to use a list as key in a dictionary or something like that. Lists are not hashable, and so they cannot be used as dictionary keys or in sets.
On another note, python gives you a stacktrace when such an error happens, and that includes file-names and line-numbers. You should be able to track down the offending code with that.
Edit About stacktraces:
cat > script.py
foo = [1,2,3]
bar = {}
bar[foo] = "Boom"
print "Never happens"
python script.py
Traceback (most recent call last):
File "script.py", line 3, in <module> // this is the file and the line-number
bar[foo] = "Boom"
TypeError: unhashable type: 'list'
You've probably attempted to use mutable objects such as lists, as the key for a dictionary, or as a member of a set. Mutable items cannot be tracked for such uses efficiently and predictably so they do not provide the hash special attribute.
The error is produced when an unhashable type is added to sets.
>>> s=set((1,2))
>>> a.add([3,4])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
I think this may be also your case. Use tuple instead of list:
>> a.add((3,4))
>>>
Maybe the line should be like this instead
totalCost = sum(map(problem.getCostOfActions,self.actions))
or if you prefer a generator expression
totalCost = sum(problem.getCostOfActions(action) for action in self.actions)
Since I can't see your code, I assumed that problem.getCostOfActions() returns the cost of a single action, as that might cause the error you are getting if self.actions is a list
Alternatively you could fix the function problem.getCostOfActions() so that it returns the total cost of a list of actions as the name suggests.
Consider adding the body of this function to your question if you want help fixing it
I had the same error with django :
food_list = ['spam' , 'more spam' , 'spam spam']
table.cum.add(food_list)
and I got error - TypeError: list objects are unhashable.
The fix is table.cum.add(*food_list)
-add * infront of list to unpack it
the model method add accepts args - (x,y,z) but not ([x,y,z])
hope it helps

Categories