Bootstrap FreeKB - Python (Scripting) - Getting Started with Dictionaries
Python (Scripting) - Getting Started with Dictionaries

Updated:   |  Python (Scripting) articles

Here is an example of how you can create a dictionary that contains no keys and no values, an empty dictionary.

#!/usr/bin/python
dictionary = {}
print(dictionary)

 

Or like this, using the dict constructor.

#!/usr/bin/python
dictionary = dict()
print(dictionary)

 

Which should print the following.

{}

 

Here is an example of how you can create a dictionary that contains keys but no values.

#!/usr/bin/python
dictionary = {
  "foo",
  "bar"
}
print(dictionary)

 

Which should print the following.

{'foo', 'bar'}

 

Here is an example of how you can create a dictionary that contains keys and values.

#!/usr/bin/python
dictionary = {
  "foo": "Hello",
  "bar": "World"
}
print(dictionary)

 

Or like this, using dict.

#!/usr/bin/python
dictionary = dict(foo = "Hello", bar = "World")
print(dictionary)

 

Which should print the following.

{'foo': 'Hello', 'bar': 'World'}

 

And here is how you can print the value of a certain key. This should print Hello in this example.

#!/usr/bin/python
dictionary = {
  "foo": "Hello",
  "bar": "World"
}
print(dictionary['foo'])

 

Let's say you reference a key that does not exist in the dictionary.

#!/usr/bin/python
dictionary = {
  "foo": "Hello",
  "bar": "World"
}
print(dictionary['bogus'])

 

This should raise a KeyError.

Traceback (most recent call last):
  File "example.py", line 6, in <module>
    print(dictionary['bogus'])
KeyError: 'bogus'

 

try except else can be used to handle KeyError.

#!/usr/bin/python
dictionary = {
  "foo": "Hello",
  "bar": "World"
}

try:
  dictionary['bogus']
except KeyError:
  print("dictionary does not contain key 'bogus'")
  pass
else:
  print(dictionary['bogus'])

 

Or, get can be used. If the key does not exist, None will be returned.

#!/usr/bin/python
dictionary = {
  "foo": "Hello",
  "bar": "World"
}
print(dictionary.get('bogus'))

 

And here is how you can loop through a dictionary.

#!/usr/bin/python3
dictionary = {
  "fruit":"apple",
  "veggy":"tomato",
  "grain":"rice"
}

for key in dictionary:
  print(f"{key} = {dictionary[key]}")

 

It's important to recognize that a dictionary is very similar to JSON, but not exactly the same.

#!/usr/bin/python
import json

dictionary =  {"foo": "Hello", "bar": "World"}
raw_json   = '{"foo": "Hello", "bar": "World"}'

print(type(dictionary))
print(dictionary)
print(type(raw_json))
print(raw_json)

 

Which should print the following, which shows that the dictionary type is dict whereas the JSON is actually a string, which can be seen by the fact that the JSON is wrapped in single quotes so that it's a string.

<type 'dict'>
{'foo': 'Hello', 'bar': 'World'}
<type 'str'>
{"foo": "Hello", "bar": "World"}

 




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 c6017d in the box below so that we can be sure you are a human.