Dictionaries

Dictionaries consists of key:value pairs. A key is unique. The syntax is

{'key':'value', 'key':'value', 'key':'value'}

Example: The SentimentIntensityAnalyzer returns polarity_scores as a dictionary of 4 key:value pairs:
from nltk.sentiment import SentimentIntensityAnalyzer as SIA
sia = SIA()
s = 'The enthusiastic programmer jumps over the quick brown fox jumps over the happy programmer jumps over the overjoyed fire fox.'
res = sia.polarity_scores(s)
print(res)
{'neg': 0.083, 'neu': 0.552, 'pos': 0.366, 'compound': 0.8481}
type(res)
dict
# Get keys:
res.keys()
dict_keys(['neg', 'neu', 'pos', 'compound'])
# Get the value for a specific key:
res['pos']
0.366
# Get all values:
res.values()
dict_values([0.083, 0.552, 0.366, 0.8481])

Loop through a dictionary

for key in res.keys():
    print(key)
neg
neu
pos
compound
for value in res.values():
    print(value)
0.083
0.552
0.366
0.8481
for key, value in res.items():
    print(key.ljust(10), ':', value)
neg        : 0.083
neu        : 0.552
pos        : 0.366
compound   : 0.8481

Create a dictionary, add and remove items

d = {'a':'ant', 'b':'bonobo', 'c':'catfish'}
# Add an item:
# The notation is the same like assigning a value to an index in a list.

d['z'] = 'zebra'

# Changing the value is done likewise:
d['c'] = 'cat'

for key, value in d.items():
    print(key, ':', value)
a : ant
b : bonobo
c : cat
z : zebra
# Remove an item:

d.pop('b')

print(d.keys())
dict_keys(['a', 'c', 'z'])
# Change a key:
# Assign the value of the key to a new key
# and remove the old key.

d['new key'] = d.pop('z')

for key, value in d.items():
    print(key.ljust(8), ':', value)
a        : ant
c        : cat
new key  : zebra

More about dictionaries

# Copying a dictionary is done in one of the two following ways:

d_copy = d.copy()
# or
d_copy = dict(d)