I have a question related to python code. I need to aggregate if the key = kv1, how can I do that?
input='num=123-456-7890&kv=1&kv2=12&kv3=0'
result={}
for pair in input.split('&'):
(key,value) = pair.split('=')
if key in 'kv1':
print value
result[key] += int(value)
print result['kv1']
Thanks a lot!!
I'm assuming you meant
key == 'kv1'
and also thekv
withininput
was meant to bekv1
and thatresult
is an emptydict
that doesn't needresult[key] += int(value)
justresult[key] = int(value)
Assuming you have multiple lines with data like:
Reading line-by-line in a file:
Or just one
string
:Console i/o:
test.txt:
results in: {'num': ['123-456-7890'], 'kv2': ['12'], 'kv': ['1'], 'kv3': ['0']}
The keys are aggregated for you.
You could do it this way, so basically just add an extra if else block dealing with the empty case for key