Reputation: 1932
Let's assume the following :
sp_sample=[{"t":1434946093036,"v":54.0},{"t":1434946095013,"v":53.0},{"t":1434946096823,"v":52.0}
I wish I could get the following result :
sp_sample=[{"t":1434946093036,"v":5400.0},{"t":1434946095013,"v":5300.0},{"t":1434946096823,"v":5200.0}
In other words, I wish I could iterate through the array and multiple v by a 100 factor.
The following only performs the multiplication on the first item, ie yields 54000 :
for i, a in enumerate(sp_sample):
a[i]['v'] = a[i]['v'] * 100
The sp_sample
is of type tuple. Using the following yields the whole array, which is not what I expect :
print sp_sample[0]
Also, tried printing sp_sample :
print sp_sample
Which returns the following (replaced the ....... for brevity) :
([{'t': 1434946093036, 'v': 54.0}, {'t': 1434946095013, 'v': 53.0}, {'t': 1434946096823, 'v': 52.0}, {'t': 1434946098612, 'v': 52.0}, {'t': 1434946100400, 'v': 51.0}, {'t': 1434946102372, 'v': 49.0},........, {'t': 1434947987823, 'v': 15.0}, {'t': 1434947989851, 'v': 12.0}, {'t': 1434947991899, 'v': 10.0}, {'t': 1434947993744, 'v': 5.0}, {'t': 1434947995599, 'v': 0.0}, {'t': 1434947997455, 'v': 0.0}, {'t': 1434947999494, 'v': 0.0}, {'t': 1434948001542, 'v': 0.0}, {'t': 1434948003417, 'v': 0.0}, {'t': 1434948005264, 'v': 0.0}, {'t': 1434948007120, 'v': 0.0}],)
print type(sp_sample) returns :
Upvotes: 2
Views: 2534
Reputation: 87064
Simply iterate over the list and update the dictionaries as you go:
sp_sample = [{"t":1434946093036,"v":54.0},{"t":1434946095013,"v":53.0},{"t":1434946096823,"v":52.0}]
for d in sp_sample:
d['v'] *= 100
>>> print(sp_sample)
[{'t': 1434946093036, 'v': 5400.0}, {'t': 1434946095013, 'v': 5300.0}, {'t': 1434946096823, 'v': 5200.0}]
This will bind in turn each dictionary in list (tuple?) sp_sample
to d
, which you then update in place. You do not need to use enumerate()
.
Note that you really need to multiply by 100, not 10000, to achieve the output that you have shown.
Update
sp_sample
is actually a tuple with a list of dictionaries as its only item. So you need to access the list in the tuple like this:
sp_sample = ([{"t":1434946093036,"v":54.0},{"t":1434946095013,"v":53.0},{"t":1434946096823,"v":52.0}],)
for d in sp_sample[0]: # N.B. access first item of tuple
d['v'] *= 100
>>> print(sp_sample)
[{'t': 1434946093036, 'v': 5400.0}, {'t': 1434946095013, 'v': 5300.0}, {'t': 1434946096823, 'v': 5200.0}]
Or, since the tuple contains only a single item you could just get rid of the tuple by:
sp_sample = sp_sample[0]
for d in sp_sample:
d['v'] *= 100
Upvotes: 8