I am getting an attribute error for the following code :
coininfo = [ {} for k in range(0,numberOftrials)]
coininfo[i].append([x,outcome(x)])
The following is the exact error screen i am getting:
Traceback (most recent call last):
File "pr1.py", line 22, in <module>
runsimulation(numberOftrials,numberOfcoins)
File "pr1.py", line 19, in runsimulation
coininfo[i].append([x,outcome(x)])
AttributeError: 'dict' object has no attribute 'append'
Any help is appreciated!
When you run
coininfo = [ {} for k in range(0,numberOftrials)]
you end up with an array of dictionaries, not an array of arrays. Thus coininfo[i] is a dictionary, and you can't append to it.
My guess is that you want to change your first line to
coininfo = [ [] for k in range(0,numberOftrials)]
so you will instead have an array of arrays. Alternative, if you mean for your output to be an array of dictionaries, you may mean to have
coininfo[i][x] = outcome(x)
instead of
coininfo[i].append([x,outcome(x)])
Related
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))
I'm writing a program to sort through csv files. It is supposed to pull lines from the files and based on whether a "donor" is already in the dictionary, either add the "donor" to the dictionary or append the information in the line to the old value. I'm getting the error statement:
error statement: File "C:/Users/riley/Desktop/Python Files/MYLATEST1.py", line 27, in
donors[donor] = [[data]]
builtins.TypeError: list indices must be integers or slices, not tuple
I'm new to python, but it seems as if python is interpreting my dictionary as a list. Is that what's going on? If so, why? Thanks for any help!
def createDonorDirect():
listoffiles = glob.glob('C:/Users/riley/Desktop/mydata//*.csv') #glob allows you to create a list of files/folders that match wildcard expression in this case all the csv files in the directory
# Create donors directory
donors = {}
for filename in listoffiles:
with open(filename) as file:
for line in file:
# line processing stuff
data = line.split(',')
donor = ''.join(data[3,5,7])
# populate data structure
if donor in donors:
donors[donor].append(data)
else:
donors[donor] = [[data]]
The reason for the error is you are assigning donor to tuple value as key, which is wrong here since tuple content multiple values.
sample problem regeneration with code:-
>>> data=['HI','Hello','How','are','you','my','name','is']
>>> donor = ''.join(data[3,5,7])
Traceback (most recent call last):
File "<pyshell#34>", line 1, in <module>
donor = ''.join(data[3,5,7])
**TypeError: list indices must be integers or slices, not tuple**
>>>
second simplified code:-
>>> data[3,5,7]
Traceback (most recent call last):
File "<pyshell#35>", line 1, in <module>
data[3,5,7]
TypeError: list indices must be integers or slices, not tuple
Tuple declaration can be little confusing sometimes.
For example: SOME_CONSTANT = 1, is same as SOME_CONSTANT = (1, ) . Both are a tuple.
On the other hand, SOME_CONSTANT = (1) will be same as SOME_CONSTANT = 1. Both are an integer.
In your case you just need to change:
donor = ''.join(data[3,5,7])
to
donor = ''.join(data[3] + data[5] + data[7])
Example:
data=['A','B','C','D','E','F','G','H']
print ''.join(data[3] + data[5] + data[7])
DFH
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.
I want to split the History_Data with , and put into an dictionary , then put the dictionary to a one dimension array then access them . But it seems have some error . How can I solve that?
here is my code
History_Data = ("2004/01/20,000006,29,28,13,33,34,32,43",
"2004/01/18,000005,36,22,44,34,46,29,37",
"2004/01/16,000004,02,13,34,44,06,40,14",
"2004/01/14,000003,29,28,13,33,34,32,43",
"2004/01/12,000002,32,15,14,29,39,20,43",
"2004/01/10,000001,30,29,18,34,19,28,12")
Dataset = ()
for Line in History_Data:
Item = {}
Parts = Line.split(",")
Item['date'] = Parts[0]
Item['serial'] = Parts[1]
Item['numbers'] = Parts[2:len(Parts)]
Dataset.append(Item)
for Element in Dataset:
print(Element)
Error message
Traceback (most recent call last):
File ".\1.py", line 18, in <module>
Dataset.append(Item)
AttributeError: 'tuple' object has no attribute 'append'
tuple is an immutable type in Python so gets no method append. For your need, use a list, Dataset = [], not a tuple, Dataset = ().
I am trying to extract the JSON object in python using Simplejson. But I am getting the following error.
Traceback (most recent call last):
File "Translator.py", line 42, in <module>
main()
File "Translator.py", line 38, in main
parse_json(trans_text)
File "Translator.py", line 27, in parse_json
result = json['translations']['translatedText']
TypeError: list indices must be integers, not str
This is my JSON object looks like,
{'translations': [{'translatedText': 'fleur'}, {'translatedText': 'voiture'}]}
and this is my python piece of code for it.
def parse_json(trans_text):
json = simplejson.loads(str(trans_text).replace("'", '"'))
result = json['translations']['translatedText']
print result
any idea on it?
json['translations'] is a list by your definition, so its indices must be integers
to get a list of translations:
translations = [x['translatedText'] for x in json['translations']]
another way:
translations = map(lambda x: x['translatedText'], json['translations'])
json['translations'] is a list of objects. To extract the 'translatedText' property, you could use itemgetter:
from operator import itemgetter
print map(itemgetter('translatedText'), json['translations'])
See the implementation of detect_language_v2() for another usage example.