Skip to content

Dictionaries

Dictionaries data structure associates values with keys. The keys allows the quick retreival of values.

Definition

dict_one = {} #Pythonic
dict_two = dict()
dict_values = {"Name": "John"}

Access

dict_values["Name"]
'John'
"John" in dict_values
False
"Jack" in dict_values
False
dict_values.get("Name", 0)
'John'
dict_values.get("Address", 0)
0
val = dict_values.get("Address")
print(val)
None

Modification

dict_values["Name"] = "Adam"
dict_values["Address"] = "USA"
len(dict_values)
2

Iterators

dict_keys = dict_values.keys()
dict_vals = dict_values.values()
dict_items = dict_values.items()
"Name" in dict_keys
True
"Name" in dict_values #Pythonic
True
"Adam" in dict_vals
True

defaultdict

The defaultdict structure allows creating a dictionary where in the event that a key does not exist, the defaultdict would add a new key with the default value passed as its parameter.

from collections import defaultdict
document = "Hello this is a test and this is another test."
word_count = defaultdict(int) 

for word in document.split(' '):
    word_count[word] += 1

word_count
defaultdict(int,
            {'Hello': 1,
             'this': 2,
             'is': 2,
             'a': 1,
             'test': 1,
             'and': 1,
             'another': 1,
             'test.': 1})