Reputation: 24121
How can I add a context variable to an existing context?
For example:
context = {'name': 'Andrew', 'age': 43}
I now want to add:
{'city': 'London'}
How can I do this without declaring the context all in one go?
Upvotes: 0
Views: 2347
Reputation: 37319
Is there something wrong with direct dict-style assignment? I don't have a Django install handy to confirm, but the docs and my memory say it should work. Assuming it does, it's more idiomatic than using update
for a single key.
context = {'name': 'Andrew', 'age': 43}
context['city'] = 'london'
Actually, that's not even a context object yet (as Daniel Roseman points out in a comment above), it's just a normal dict. Direct assignment also works after you've created the context object, as shown in the linked docs. Assuming your Django tag on the question and the reference to contexts means you're working with Django contexts at some point.
Upvotes: 5
Reputation: 505
In dictionary you can use update to append the data.You can use following code to do so:
context = {'name': 'Andrew', 'age': 43}
context.update({'city': 'London'})
print context
output:
{'city': 'London', 'age': 43, 'name': 'Andrew'}
Upvotes: 4
Reputation: 12158
you can use the .update
method:
>>> context = {'name': 'Andrew', 'age': 43}
>>> context.update({'city': 'London'})
>>> context
{'age': 43, 'city': 'London', 'name': 'Andrew'}
Upvotes: 2