Bootstrap FreeKB - Python (Scripting) - Append to a dictionary
Python (Scripting) - Append to a dictionary

Updated:   |  Python (Scripting) articles

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'}]}

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 770752 in the box below so that we can be sure you are a human.