I have a scenario , where I am trying to get index position of value
My code :
a_set = {22,56,26}
print(a_set[56])
Getting below error
Traceback (most recent call last):
File "<string>", line 5, in <module>
TypeError: 'set' object is not subscriptable
Expected output :
1 -> This the position of 56 from set
The error is explaining a lot here: sets in Python are not subscriptable.
They dont have order relation.
According to your code example, you are trying to ask weather a value exists in the set, right?
In Python you can do it with in operator:
>> print(36 in a_set)
True
or
if (36 in a_set):
my_function()
Sets are by definition completely unordered and unindexed, you cannot get the information with an index directly as that is not what they were made for. As a workaround, you can simply convert the set to a list that is both indexed and ordered.
a_set = {22,56,26}
print(list(a_set)[3]) # converts the set into and displays it's third entry.
To solve your problem, you can use .index() on the new list such as this:
a_set = {1,2,3}
print(list(a_set).index(1))
Related
What's wrong with that code? When I run it tells me this:
Traceback (most recent call last):
line 24, in <module>
people.append(Dict)
AttributeError: 'str' object has no attribute 'append'
My code:
live = 1
while live == 1:
#reading Database
dataRead = open ("db.txt","r")
if dataRead.read() != " ":
dataRead.close()
people = open ('db.txt','r').read()
do = input ('What Do You Want ? (Search , add) :\n')
#add people
if do == 'add':
#Get The New Data
n_Name = input ('enter the new name:\n')
n_age = input ('enter the new age:\n')
#new Dict
Dict = {'Name:':n_Name,'age':n_age}
people.append(Dict)
#adding people to file
dataWrite = open ("db.txt","w")
dataWrite.write(str(people))
dataWrite.close()
live = 0
The problem is, on line 24, you try to append a dictionary to a string. When you read the db file, it read it as a string. Also the code is really messy and there are a lot better ways to do it. But that's besides the point, the append() method is for lists and the variable "people" is a string, according to your error output.
It says that people is str then it doesn't have an append method. You should just concatenate strings to get them together.
Do:
people += '<append string>'
Have in mind you are trying to append a dictionary to a string. This will throw TypeError cause those type of elements can't be concatenated that way. You should do first: str(dict) to concatenate them.
You're also using a reserved word like dict as a variable. Change it to my_dict or other allowed name.
I am having trouble reading data in python. A sample of one of the rows is:
foo_brackets='{"KEY2":[{"KEY2a":[{"KEY2a1":"4","KEY2a2":"5"},{"KEY2a1":"6","KEY2a2":"7"}],"KEY2b":"8"}],"KEY3":"9"}'
When I load with json, the value for KEY2 is read in as a list, because of the brackets, which then prevents me from getting at my desired result, which is the value of KEY2b:
>>> import json
>>> foo_brackets_json=json.loads(foo_brackets)
>>> foo_brackets_json['KEY2']['KEY2b']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not str
I could just try to remove the brackets, but there actually is a value that should be a list, KEY2a. You can see this if I strip out all the brackets and try to convert to JSON:
>>> foo_no_brackets='{"KEY2":{"KEY2a":{"KEY2a1":"4","KEY2a2":"5"},{"KEY2a1":"6","KEY2a2":"7"},"KEY2b":"8"},"KEY3":"9"}'
>>> json.loads(foo_no_brackets)
# Traceback omitted since it's just the python error
ValueError: Expecting property name: line 1 column 45 (char 45)
foo_brackets does appear to be valid JSON (I tested here, with the quotes removed) and got the following:
{
"KEY2":[
{
"KEY2a":[
{
"KEY2a1":"4",
"KEY2a2":"5"
},
{
"KEY2a1":"6",
"KEY2a2":"7"
}
],
"KEY2b":"8"
}
],
"KEY3":"9"
}
Question:
Is there a way for me to read objects like foo_brackets so that I can call foo_brackets_json['KEY2']['KEY2b']?
foo_brackets_json['KEY2'] references a list, here with one element.
You'll have to use integer indices to reference the dictionaries contained in that list:
foo_brackets_json['KEY2'][0]['KEY2b']
Don't try to remove the brackets; there could be 0 or more nested dictionaries here. You'll have to determine what should happen in those cases where you don't have just 1 nested dictionary.
The above hardcoded reference assumes there is always at least one such a dictionary in the list, and doesn't care if there are more than one.
You could use looping to handle the 0 or more case:
for nested in foo_brackets_json['KEY2']:
print(nested['KEY2b'])
Now you are handling each nested dictionary, one by one. This'll work for the empty list case, and if there is more than one.
You could make having 0 or more than one an error:
if len(foo_brackets_json['KEY2']) != 1:
raise ValueError('Unexpected number of results')
etc. etc. It all depends on your actual use-case.
I am trying to write a targeting priority script for an AI. My goal is to rank targets based on their score of damage_per_shot / rate_of_fire and reorder the list based on highest targeting priority. I finally hit an error I didn't know how to work around however. 'NoneType' object has no attribute 'get'
I am very new to Python and built this mostly by Googling the terms I would have used in Ruby. I would also appreciate suggestions about how to do this in the correct Python "style" if I made any major errors.
enemyList=[{"id":1,"damage_per_shot":10,"rate_of_fire":2},{"id":3,"damage_per_shot":0,"rate_of_fire":0},{"id":2,"damage_per_shot":14,"rate_of_fire":2}]
#enemyList=unit_client.ask_nearest_enemy()
print(enemyList)
aDict = {}
for item in enemyList:
if(item["rate_of_fire"]!=0):
currScore=float(item["damage_per_shot"]/item["rate_of_fire"])
aDict[item['id']] = currScore
def focus_fire2(data=None, *args, **kawargs):
print("===ff2===")
target_id=sorted(aDict, key=data.get)
print(target_id)
print("attacking: "+str(id))
#unit_client.do_attack(key)
##remove item from list
if(len(aDict)>0):
del aDict[target_id] #remove the object from the dict after done
print(aDict)
focus_fire2()
else:
return 0
#unit_client.when_item_destroyed(target, aDict.pop(key,None))
#unit_client.when_item_destroyed(target, focus_fire2)
focus_fire2()
The traceback looks like
[{'damage_per_shot': 10, 'id': 1, 'rate_of_fire': 2}, {'damage_per_shot': 0, 'id
': 3, 'rate_of_fire': 0}, {'damage_per_shot': 14, 'id': 2, 'rate_of_fire': 2}]
===ff2===
Traceback (most recent call last):
File "ffire.py", line 26, in <module>
focus_fire2()
File "ffire.py", line 13, in focus_fire2
target_id=sorted(aDict, key=data.get)
AttributeError: 'NoneType' object has no attribute 'get'
Just replace
sorted(aDict, key=data.get)
by
sorted(aDict, key=aDict.get)
In your function focus_fire2, you set data to None by default in the arguments of the function definition. Unless you set it to something other than None when you call it, like focus_fire2(data=something), then it's equal to None when you do, data.get() later on. And there lies your error I think. You are treating a NoneType like a dict. If you're calling get on it, you probably should be setting it equal to some dict or other.
You get an error, because run function without arguments, and by default data have a None type. And for me it's not good idea, set default value as None for non optional arguments. You need run function with argument focus_fire2(aDict), or change target_id=sorted(aDict, key=data.get) to target_id=sorted(aDict, key=aDict.get, reverse=True) you get in target_id, list of sorted key from aDict, where first value is higher. But target_id is a list and this code is wrong del aDict[target_id]. What must be in target_id?
I'm pretty sure that my error is a very small and stupid thing but I'm not capable to see it!! :(
I have a defined dictionary: self.names_to_nodes, and I want to access to one of its members with the key that I have.
Here is a piece of my code:
print "Result " + str(len( self.names_to_nodes))
if i in self.names_to_nodes:
print "ESTA"
member = self.names_to_nodes.get(i)
ancestrosA.append(member.get_parent())
And I get this exit and this error:
Result 17
ESTA
143 print "ESTA"
144 member = self.names_to_nodes.get(i)
145 ancestrosA.append(member.get_parent())
146 i = member.get_parent()
147 ancestrosA.append(self.founder)
AttributeError: 'NoneType' object has no attribute 'get_parent'
How is this possible???
Thanks for your help! How get(i) is not finding the element if the key is in the dictionary?
BR,
Almu
You need to move the lookup inside the if statement if you want to make sure it exists before checking:
if i in self.names_to_nodes:
print "ESTA"
# only does a lookup if the key exists
member = self.names_to_nodes[i]
ancestrosA.append(member.get_parent())
You check if it exists but still check i outside the if so whether i exists or not you always do a lookup.
dict.get returns a value whether the key is in the dictionary or not. Example:
>>> x = {1:2}
>>> print(x.get(100))
None
Try using regular item access instead. Then your code will raise an exception if you try to get a nonexistent value. Example:
>>> x = {1:2}
>>> print(x[100])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 100
(Readers may ask, "but how could i not be a key in the dictionary? 'ESTA' was printed, and that only occurs when the membership test successfully passes". I'm assuming that this code is inside a for loop that changes the value of i, and the printed 'ESTA' is from the previous iteration, which ran without problems.)
This is the simplest of exercises. I just don't understand why it wont work.
Here's my code:
hobbies = []
for i in range(3):
hobby = raw_input("Name a hobby")
hobbies = hobbies.append(hobby)
Basically I want to ask my user 3 times to name one of his hobbies, and store them in a list. But for some reason I'm getting this error,
Traceback (most recent call last):
File "C:/Python27/hobbies.py", line 4, in <module>
hobbies = hobbies.append(hobby)
AttributeError: 'NoneType' object has no attribute 'append'
which I don't really understand.
The problem is that append() will change the list in-place. And when you call this function no value is returned.
The first time you get a None value for the variable hobbies. The second time you try to call the append() method for a None value...
You should not use hobbies = hobbies.append(). Instead use hobbies.append() only.