Reputation: 615
I have a list that contains dicts like this:
[
{'match_id': 1L, 'player_b_id': 2L, 'round_id': 1L, 'match_winner_id': 2L, 'match_date': datetime.date(2016, 3, 9), 'player_a_id': 1L, 'tournament_id': 1L},
{'match_id': 2L, 'player_b_id': 4L, 'round_id': 1L, 'match_winner_id': 4L, 'match_date': datetime.date(2016, 3, 10), 'player_a_id': 3L, 'tournament_id': 1L}
]
and I'm wondering how can I modify each element's 'match_date'
to a string date. I know this can be accomplished using a regular loop but I'm trying to learn about list comprehensions and got stuck in this part.
I tried something like this without success:
matchesData = [str(v) if k == 'match_date' else v for k, v in enumerate(matchesData)]
Upvotes: 0
Views: 44
Reputation: 1124828
If you must use a list comprehension, then you must also rebuild each dictionary:
matchesData = [{k: str(v) if k == 'match_date' else v for k, v in d.items()}
for d in matchesData]
or use
matchesData = [dict(d, match_date=str(d['match_date']))
for d in matchesData]
The first example uses a dictionary comprehension, that simply creates a new dictionary from the old by looping over each key-value pair. For the 'match_date'
key the values is passed through the str()
function. This means the match_date
key is entirely optional.
The second version requires 'match_date'
to exist, and creates a copy of the original dictionary with the dict()
function, adding in an extra key (which will replace the original 'match_date'
key-value pair from d
).
Demo:
>>> from pprint import pprint
>>> matchesData = [
... {'match_id': 1L, 'player_b_id': 2L, 'round_id': 1L, 'match_winner_id': 2L, 'match_date': datetime.date(2016, 3, 9), 'player_a_id': 1L, 'tournament_id': 1L},
... {'match_id': 2L, 'player_b_id': 4L, 'round_id': 1L, 'match_winner_id': 4L, 'match_date': datetime.date(2016, 3, 10), 'player_a_id': 3L, 'tournament_id': 1L}
... ]
>>> pprint([{k: str(v) if k == 'match_date' else v for k, v in d.items()} for d in matchesData])
[{'match_date': '2016-03-09',
'match_id': 1L,
'match_winner_id': 2L,
'player_a_id': 1L,
'player_b_id': 2L,
'round_id': 1L,
'tournament_id': 1L},
{'match_date': '2016-03-10',
'match_id': 2L,
'match_winner_id': 4L,
'player_a_id': 3L,
'player_b_id': 4L,
'round_id': 1L,
'tournament_id': 1L}]
>>> pprint([dict(d, match_date=str(d['match_date'])) for d in matchesData])
[{'match_date': '2016-03-09',
'match_id': 1L,
'match_winner_id': 2L,
'player_a_id': 1L,
'player_b_id': 2L,
'round_id': 1L,
'tournament_id': 1L},
{'match_date': '2016-03-10',
'match_id': 2L,
'match_winner_id': 4L,
'player_a_id': 3L,
'player_b_id': 4L,
'round_id': 1L,
'tournament_id': 1L}]
Upvotes: 3