trying to increment the list value if key exits - python

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

Related

I don't know what that error means and how to solve this. I want to add Country key and France value to the dictionary

dictionary_of_spliting = {"Food":"Honey",
"Trash1":"some",
"Trash2":"some",
"Trash3":"your",
"Thing":"resorces"}
for keys in dictionary_of_spliting:
if var <= 12:
dictionary_of_spliting["Country"] = "France"
Traceback (most recent call last)
File "C:\Users\IK\PycharmProjects\More sting methods.py", line 20, in <module>
for keys in dictionary_of_spliting:
RuntimeError: dictionary changed size during iteration
You are modifying a dict while iterating through it - this is not allowed, as it breaks the underlying iterator.
You can replace
for keys in dictionary_of_splitting
with
for keys in list(dictionary_of_splitting)
to make a copy of the entries and prevent this issue. You can also use dictionary_of_splitting.keys() if using python2

float object not subscriptable (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

How to remove the following error?

The question was to find the symmetric difference between two sets without using the the corresponding method !
from future import print_function
M=int(raw_input())
X=map(int,raw_input().split())
N=int(raw_input())
Y=map(int,raw_input().split())
mys=set()
mys1=set()
for i in X:
mys.add(i)
for i in Y:
mys1.add(i)
un=mys.union(mys1)
inx=mys.intersection(mys1)
sd=un.difference(inx)
w=list(sd)
w=w.sort()
for i in (w):
print(w[i],end=' ')
Error occured is:
Traceback (most recent call last): File "hackset.py", line 18, in
<module>
for i in len(w): TypeError: object of type 'NoneType' has no len()**
list.sort does not return a new sorted function. It just sort the list (return None).
If you want to get a new list sorted, use sorted instead.
There's another issue. Iterating a list yields elements, you don't need to index them to get items; Just iterate without indexing.
for item in w:
print(item, end=' ')
Your error is here:
w=w.sort()
The return type for w.sort() is 'None'. The sort() method is in-place. Change it to just:
w.sort()

converting tuple to dictionary in python

I am trying to convert a line of string to dictionary where i am facing an error.
here is what i have and what i did:
line="nsd-1:quorum"
t=tuple(line.split(":"))
d=dict(t)
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
d=dict(t)
ValueError: dictionary update sequence element #0 has length 5; 2 is required
Basically, what i want to achieve is to have a key value pair.
So if i have set of values separated by a ":", i want to have it as a key whatever is before the colon and after the colon needs to be the value for the key.
example: if i take the above string, i want "nsd-1" as my key and "quorum" as value.
Any help is appreciated.
Thanks
Wrap it in a list:
>>> dict([t])
{'nsd-1': 'quorum'}
There's also no need to convert the return value of split to a tuple:
>>> dict([line.split(':')])
{'nsd-1': 'quorum'}
Put t inside an empty list, like this:
d=dict([t])

How to extract data using json in python

I have an issue with a code I've written. When I run the code I get an error :
Traceback (most recent call last):
File "test23_json_users.py", line 23, in <module>
for user_dict in abc['user_account']['sip_id']:
TypeError: list indices must be integers, not str
The code:
result = '[{"user_account":[{"address":null,"name":null,"country":null,"password":"****","extension":"1112","sip_id":"23001#50.50.50.201","sip_name":"23001","user_id":7973712,"locked":false,"created":null,"h323_name":"1101","city":null,"email":null,"phone":null,"zip":null},{"address":null,"name":null,"country":null,"password":"****","extension":"1113","sip_id":"23002#50.50.50.201","sip_name":"23002","user_id":8847075,"locked":false,"created":null,"h323_name":"1102","city":null,"email":null,"phone":null,"zip":null},{"address":null,"name":null,"country":null,"password":"****","extension":"1114","sip_id":"23003#50.50.50.201","sip_name":"23003","user_id":3680630,"locked":false,"created":null,"h323_name":"1103","city":null,"email":null,"phone":null,"zip":null},{"address":null,"name":null,"country":null,"password":"****","extension":"1115","sip_id":"23004#50.50.50.201","sip_name":"23004","user_id":136391,"locked":false,"created":null,"h323_name":"1104","city":null,"email":null,"phone":null,"zip":null},{"address":null,"name":null,"country":null,"password":"****","extension":"1116","sip_id":"23005#50.50.50.201","sip_name":"23005","user_id":5692227,"locked":false,"created":null,"h323_name":"1105","city":null,"email":null,"phone":null,"zip":null},{"address":null,"name":null,"country":null,"password":"****","extension":"1117","sip_id":"23006#50.50.50.201","sip_name":"23006","user_id":7559026,"locked":false,"created":null,"h323_name":"1106","city":null,"email":null,"phone":null,"zip":null},{"address":null,"name":null,"country":null,"password":"****","extension":"1118","sip_id":"23007#50.50.50.201","sip_name":"23007","user_id":3226075,"locked":false,"created":null,"h323_name":"1107","city":null,"email":null,"phone":null,"zip":null},{"address":null,"name":null,"country":null,"password":"****","extension":"1119","sip_id":"23008#50.50.50.201","sip_name":"23008","user_id":6184875,"locked":false,"created":null,"h323_name":"1108","city":null,"email":null,"phone":null,"zip":null},{"address":null,"name":null,"country":null,"password":"****","extension":"1120","sip_id":"23009#50.50.50.201","sip_name":"23009","user_id":1711112,"locked":false,"created":null,"h323_name":"1109","city":null,"email":null,"phone":null,"zip":null},{"address":null,"name":null,"country":null,"password":"****","extension":"1121","sip_id":"23010#50.50.50.201","sip_name":"23010","user_id":5383101,"locked":false,"created":null,"h323_name":"1110","city":null,"email":null,"phone":null,"zip":null}]}'
params = result[result.find('{"'):]
#print params
abc = json.loads(params)
# Here I'm trying to extract just sip_id from the string result using json.
# I am not able to figure out what went wrong .
for user_dict in abc['user_account']['sip_id']:
print 'usersname : %s' % (user_dict['sip_id'])
Change
for user_dict in abc['user_account']['sip_id']:
to
for user_dict in abc['user_account']:
abc['user_account'] is supposed to be a list.
A list a=['hello',1,2,'people'] has 4 elements accessed by indexes a[0] through a[3].
A dictionary d={'a':1,'b':2} has keys and values. In this case d['a'] has value 1, d[b'] has 2.
If you want to access something in abc['user_account'], type abc['user_account'][42]. If you want to iterate over it
for a in abc['user_account']:
print a

Categories

Resources