Why might python be interpreting my dictionary as a list? - python

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

Related

Find highest number from a list (given in a txt file) using import (function) in python

I am a beginner and trying to solve a problem.
- Find the highest number in a list (without using max() function) with below instructions
create a text file which has a list
create a function to identify highest value in a list
in a separate program, read the text file created in step# 1 and using function from step #2 above find the highest value in the list given in text file
Solution Tried:
I created a text file with a list in a folder [23, -1, 5, 4]
created a function (funcion_list.py) to find the highest value in list
def max_item(list):
maximum = 0
for value in list:
if value > maximum:
maximum = value
return maximum
in my playground.py program, I imported the function max_item(list), read the list from the text file and passed it as an argument in the function to find the highest number in the list
from function_list import max_item
new_list = []
with open("file1.txt", "r") as f:
for line in f:
print(line.rstrip("\n"))
new_list.append((line))
print(max_item(new_list))
Output:
I am able to read the appended file but I am getting below error instead of getting highest value printed.
Traceback (most recent call last):
File "playground.py", line 13, in <module>
print(max_item(new_list))
^^^^^^^^^^^^^^^^^^
File "function_list.py", line 4, in max_item
if value > maximum:
^^^^^^^^^^^^^^^
TypeError: '>' not supported between instances of 'str' and 'int'
Could you please help in pointing what wrong am I doing?
open will read everything as a string. You need to convert it to an int before adding it to the list.
Change this line
new_list.append((line))
to
new_list.append((int(line)))

Python: How to convert a long number into string?

I was trying to transform this long number data inside tuple into a string so I can preserved its value when I send it to JSON (The file with this data inside is named b.json)
"ecc": [
79849177969901016848164770310957289409900866592060952979899491148125256206126,
80012691714024297247210932953164632591330351085279802419411702853992977368435
]
So I try to run this command in Python
with open('b.json', 'r') as editfile:
data2 = json.load(editfile)
tmp = data2["ecc"]
tmp = [tuple(str(x) for x in tup) for tup in tmp]
data2["ecc"] = tmp
But I got this result
Traceback (most recent call last):
File "temp-hum-log.py", line 94, in <module>
tmp = [tuple(str(x) for x in tup) for tup in tmp]
TypeError: 'long' object is not iterable
So what should I do to convert this long number into string?
You went one level to deep, it's trying to iterate over this long number like it would iterate over list or string.
Try this:
with open('b.json', 'r') as editfile:
data2 = json.load(editfile)
tmp = data2["ecc"]
tmp = [str(number) for number in tmp]
data2["ecc"] = tmp
Also there is a special Decimal class for storing long number as string and you can run mathematic operations on them.

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.

List range is being taken as tuple rather than integers

I am trying to fetch elements from a list as per following code:
"data" is a string containing some data from which i am taking out values of start and end offset.
I am then multiplying the start and end Offset by 4 to calculate start,endOffsetAsPerPage.
startOffset = data.split(",,")[1].split(":")[1];
endOffset = data.split(",,")[2].split(":")[1];
startOffsetAsPerPage = int(startOffset)*4;
endOffsetAsPerPage = int (endOffset)*4;
FilteredData = CassandraData[int(startOffsetAsPerPage),int(endOffsetAsPerPage)];
While executing, i am facing following error:
Traceback (most recent call last):
File "CassandraDataAPIResultValidator.py", line 55, in <module>
FilteredData = CassandraData[int(startOffsetAsPerPage),int(endOffsetAsPerPage)];
TypeError: list indices must be integers, not tuple
Can you please help here.
Thanks in advance.
You are using a comma:
FilteredData = CassandraData[int(startOffsetAsPerPage),int(endOffsetAsPerPage)]
# ^
A comma there makes it a tuple, not a slice.
Use a colon instead:
FilteredData = CassandraData[int(startOffsetAsPerPage):int(endOffsetAsPerPage)]
# ^
Note that Python doesn't need to use semicolons at the ends of lines.

How to put an dictionary to an array?

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

Categories