The obvious (and long) solution would be the simple iterative way:
>>> l = [ {'a' : 1, 'b' : 2}, {'a' : 3, 'f' : 4} ]
>>> for i in l:
... i['c'] = 6
...
>>> print l
[{'a': 1, 'c': 6, 'b': 2}, {'a': 3, 'c': 6, 'f': 4}]
This works, but it's not very nice. When you start to get comfortable with Python after an OOP and/or procedural language, you realise that there's a whole new world hidden in the functional way of doing things. Your first attempt at solving this problem with list comprehension might look like this:
>>> l = [ {'a' : 1, 'b' : 2}, {'a' : 3, 'f' : 4} ]
>>> [i['c'] = 6 for i in l]
File "
[i['c'] = 6 for i in l]
^
SyntaxError: invalid syntax
Sadly, assignments don't work in this instance. However, dictionaries have the convenient update method, that does just this:
>>> l = [ {'a' : 1, 'b' : 2}, {'a' : 3, 'f' : 4} ]
>>> [i.update ({'c' : 6}) for i in l]
[None, None]
>>> print l
[{'a': 1, 'c': 6, 'b': 2}, {'a': 3, 'c': 6, 'f': 4}]
The syntax might look a bit hairy at first, because update takes a dictionary and merges it's values to the one that the method is called upon, keeping the values that are missing from the new dictionary.
Happy coding!
No comments:
Post a Comment