1

I have a dictionary inside list like this:

a = [{'valid': True, 'power': None, 'altitude': 0.0, 'time': datetime.datetime(2014, 4, 7, 16, 5, 55), 'longitude': 47.938, 'course': 0.0, 'address': None, 'latitude': 29.3309, 'speed': 0.0, u'id': 3L, 'device_id': 1L}] 

I only want to play with time key and put everything same. For example:

[i+timedelta(5) for i in a] 

This works but return time on list like this: [.........] which is understandable. But what I want is:

Change the value of time on the original list itself like:

a = [{'valid': True, 'power': None, 'altitude': 0.0, 'time': NEW VALUE, 'longitude': 47.938, 'course': 0.0, 'address': None, 'latitude': 29.3309, 'speed': 0.0, u'id': 3L, 'device_id': 1L}] 

How to do this?

2 Answers 2

2

Use a simple for-loop. List comprehensions are used to create new lists, don't use them for side-effects.

it = iter(dct['time'] for dct in a) tot = sum(it, next(it)) for dct in a: dct['time'] = tot 

Another way to sum the dates will be to use reduce()(functools.reduce in Python 3):

>>> dates = [dct['time'] for dct in a] >>> reduce(datetime.datetime.__add__, dates) datetime.datetime(2014, 4, 7, 16, 5, 55) 
Sign up to request clarification or add additional context in comments.

8 Comments

But How to get individual values of time and add.
@user2032220 I don't understand what you meant by individual values of time. And please don't delete the question once you've got your answer, I almost reported this to a moderator.
My list has more than one dictionary, I want to add to every time field.
@user2032220 You mean replace all the time fields with the total time?
Yes, that's what I meant.
|
0

Make sure you return an element, which is dictionary in this case. Otherwise your dictionary might get updated (if written correctly), but will not reappear as an element of the resulting list:

def update(item_dict): item_dict['time'] = item_dict['time'] + timedelta(5) return item_dict [update(item_dict) for item_dict in a] 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.