float object not subscriptable (python) - python

So I am creating 10 dictionaries from a data-frame.
I have already done 3 for each row, but I have decided to do one for every column in my data-frame. When I add the 7 additional dictionaries, I get a float object not subscriptable error. What's confusing is, I had already added the additional 7 dictionary entries for a few other rows. Even more confusing, the error is on a line where the dictionary entries had already been successfully assigned and not for the entries I'm adding to one of the 7 additional dictionaries. Here's my code, please help if you can.
pace[b[1]] = bList[1]
offEff[b[1]] = bList[9]
defEff[b[1]] = bList[10]
ast[b[1]] = bList[2]
to[b[1]] = bList[3]
orr[b[1]] = bList[4]
drr[b[1]] = bList[5]
rebr[b[1]] = bList[6]
effFG[b[1]] = bList[7]
tsPer[b[1]] = bList[8]
I'm using JupyterLab, if that helps.

You should check if the bList is a list object.According to your description,the bList may be a float in your code:
>>> a=1.0
>>> a[1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'float' object is not subscriptable

Related

accessing nested dictionaries when you know the nested key?

This one is probably pretty easy, but I can't figure it out! Suppose I have a dictionary with a nested dictionary, that I know the nested dictionary key that I can store in a variable, how would I access this value?
k = 'mynested'
nestedk = 'blah'
x = {}
x['mynested'] = {}
x['mynested']['blah'] = 1
print(x[k[nestedk]])
throws error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: string indices must be integers
There is a slight mistake in your last line print(x[k[nestedk]]). This line actually means that you are treating the k variable as a list which is actually a string and the characters of the string can only be accessed by an integer index and not by a string index.
Change the last line to the below
print(x[k][nestedk])
You can get it with x[k][nestedk]. You can access the values similar to assigning values inside dictionary. As you are assigning
X[k] = {}
and x[k][nestedk] = 1
The value is 1 and key for nested object is k so initially we get the inner dictionary by x[k] and then we get the value using nested key in your case nestedk.
Thus you have to correct your print statement like below
print(x[k][nestedk])

Corresponding dictionary key from single list value?

I am looping through a folder, finding the file name, and then trying to associate the file name I found to a value in a dictionary. I will then hopefully take the dictionary value for each file and use it for something else.
When extracting the file name it comes out as a list.
The code below shows exactly what I get. 'fileName' comes out as ['2_data'].
I need to find the corresponding dictionary value to this list value. "data2"
how would I go about this?
# dict
csvdict = ({"1_Data" : "data1",
"_2_data" : "data2",})
# example name
nameData = 'C:/folder/1/2\3\3\CSV Files\\2_data.csv'
csvName = (re.findall('CSV Files[^\w]+([\w\d\s-]+)', nameData))
print(csvName)
when I try this code I get an TypeError: unhashable type: 'list' error. I do not know how to convert the list value to something the dictionary will read.
if csvName in csvdict:
print(csvdict[csvName])
Error:
TypeError Traceback (most recent call last)
<ipython-input-71-86fc5d1ebca7> in <module>()
22 #csvdict[fileName]
23 #DICTIONARY ATTMEPT**********************************************************
---> 24 if csvName in csvdict:
25 print(csvdict[csvName])
26
TypeError: unhashable type: 'list'
You can't use a list as a dictionary key (because they're unhashable as the error message states).
The following avoids the issue:
if csvName[0] in csvdict:
print(csvdict[csvName[0]])

trying to increment the list value if key exits

for line in open('transactions.dat','r'):
item=line.rstrip('\n').split(',')
custid=item[2]
amt=item[4]
if custid in cust:
amt1=int(cust[custid])+int(amt)
cust[custid]=amt1
else:
cust[custid]=[amt]
well i am trying to check if customer id already is there in dictionary then simply add the previous amount and new amount in that customer. Otherwise add that amount in a new position in list. But i am getting error:
Traceback (most recent call last):
File "<pyshell#74>", line 7, in <module>
amt1=int(cust[custid])+int(amt)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'
some transaction data is like:
101300101,2016-09-03,376248582,1013,10.92
109400132,2016-09-03,391031719,1094,36.72
136100107,2016-09-03,391031719,1361,28.77
Did you try using defaultdict? It would make your job much easier.
from collections import defaultdict
cust = defaultdict(int)
for line in open('transactions.dat','r'):
item=line.rstrip('\n').split(',')
custid=item[2]
amt=item[4]
cust[custid] += float(amt)
and why do you try to cast amt to int? Looks like it's not an integer in the sample lines you posted. If you really want to use integer change float(amt) to int(float(amt)).

how to make my list to append different type data in python?

The list in python can load different type of data.
>>> x=[3,4,"hallo"]
>>> x
[3, 4, 'hallo']
How can i define a multi-dim list to load different type of data?
>>> info=['']*3
>>> info[0].append(2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'append'
I want to make info to be a multi-dim list,info[0] can load character and number.
Create an empty list of lists first:
info = [[] for _ in range(3)]
info[0].append(2)
info[1].append("test")
info will then look like:
[[2], ['test'], []]
Quite simply you are trying to append to a string that happens to be contained in a list. But you can't append to a string (string concatenation is something else). So either use string concatenation (if that was what you intended), or use an empty list as a container inside the list.
l = [[],[]]
is a list with two elements, two empty lists.
l.append('something')
gives you
[[],[],'something']
but l[0].append('something') would have given you:
[['something'],[]]
Instead of append, do it as follows:
>>> info=['']*3
>>> info[0] += '2' #if you want it stored as a string
Or
>>> info[0] = int(info[0]+'2') #if you want it stored as an int

How do I unpack a list with fewer variables?

k = [u'query_urls', u'"kick"', u'"00"', u'msg=1212', u'id=11']
>>> name, view, id, tokens = k
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: too many values to unpack
I need to provide 5 variables to unpack this list. Is there a way to unpack with fewer, so that tokens gets the rest of the list. I don't want to write another line to append to a list....
Thanks.
Of course I can slice a list, assign individually, etc. But I want to know how to do what I want using the syntax above.
In Python 3 you can do this: (edit: this is called extended iterable unpacking)
name, view, id, *tokens = k
In Python 2, you will have to do this:
(name, view, id), tokens = k[:3], k[3:]

Categories

Resources