How to put an dictionary to an array? - python

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 = ().

Related

Don't understand the cause of this AttributeError

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.

Why might python be interpreting my dictionary as a list?

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

Appending raw input to a list

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.

Attribute Error in python

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)])

Python JSON Google Translator extraction problem

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.

Categories