Karnivaurus
Karnivaurus

Reputation: 24121

Adding a context variable to an existing context

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

Answers (3)

Peter DeGlopper
Peter DeGlopper

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

jack
jack

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

ch3ka
ch3ka

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

Related Questions