
Let's say you have an empty dictionary that contains no keys.
#!/usr/bin/python
dictionary = {}
Here is how you can append keys that contain no value to the dictionary.
#!/usr/bin/python
dictionary = {}
dictionary["foo"] = None
dictionary["bar"] = None
print(dictionary)
Which should return the following.
{'foo': None, 'bar': None}
And here is how you can append keys that contain a value to the dictionary.
#!/usr/bin/python
dictionary = {}
dictionary["foo"] = "hello"
dictionary["bar"] = "world"
print(dictionary)
Which should return the following.
dictionary = {'foo': 'hello', 'bar': 'world'}
Let's say you have the following dictionary that already contains key value pairs.
#!/usr/bin/python
dictionary = {
"foo": "Hello",
"bar": "World"
}
= can be used to replace/overwrite a key/value pair in a dictionary or append a new key/value pair to the dictionary.
In this example, since the dictionary does not contain the "grain" key, this will append grain: veggy to the dictionary.
#!/usr/bin/python
dictionary = {
"fruit": "apple",
"veggy": "pepper"
}
dictionary["grain"] = "rice"
print(dictionary)
In this example, since the dictionary already contains the "foo" key, this will update the value of the foo key to be "goodbye".
#!/usr/bin/python
dictionary = {
"foo": "Hello",
"bar": "World"
}
dictionary["foo"] = "goodbye"
print(dictionary)
+= can be used to append a value to a key in the dictionary. In this example, "goodbye" will be appended to the foo key.
#!/usr/bin/python
dictionary = {
"foo": "Hello",
"bar": "World"
}
dictionary["foo"] += "goodbye"
print(dictionary)
Which should return the following.
dictionary = {'foo': 'hellogoodbye', 'bar': 'world'}
Let's say the dictionary contains a list. += can be used to append a value to the list in the dictionary. In this example, "production" will be appended to the environments key/list.
#!/usr/bin/python
dictionary = {
"environments": [ 'development', 'staging' ]
}
dictionary['environments'] += ['production']
print(dictionary)
Which should return the following.
dictionary = {'environments': ['development', 'staging', 'production']}
And here is how you can append a dictionary to a dictionary list.
#!/usr/bin/python
dictionary = {
"employees": [ ]
}
dictionary['employees'] += [{"name": "John Doe"}]
dictionary['employees'] += [{"name": "Jane Doe"}]
print(dictionary)
Which should return the following.
{'employees': [{'name': 'John Doe'}, {'name': 'Jane Doe'}]}
Let's say you submit a GET request to an API URL which returns response JSON. In this scenario, to append to the response, you'll almost always want to store the response JSON in a new variable and then append to the new variable.
#!/usr/bin/python
response = requests.get("https://api.example.com/foo")
data = response.json()
data['employees'] += [{"name": "John Doe"}]
data['employees'] += [{"name": "Jane Doe"}]
print(dictionary)
Did you find this article helpful?
If so, consider buying me a coffee over at