简体   繁体   中英

Python list Comprehension inside dictionaries

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?

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)

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM