Some time ago, I wrote an article about defaultdict in Python here – vitoshacademy.com/python-defaultdict-object-or-how-to-avoid-the-key-error. Now, I have decided to make a video about it and increase the scope with standard dictionary functions and an advanced class, that checks whether the value is recorded under a key with string or integer and returns the value, if it is found under any of these.
So, let’s start. We can have the following functions to a dictionary:
General functions of a dictionary
- my_dict.items()
- list(my_dict.items())
- list(my_dict.items())[2:]
- my_dict.keys()
- list(my_dict.keys())
- my_dict.get(key, value-if-key-not-present)
- my_dict.pop(key)
- my_dict.popitem()
- # this one pops an item, that should be somehow random, as the dictionaries are unordered
- my_dict.update({key:value})
- if the key is not found, a new key-value pair is written
- if the key is found, its value is overwritten
- my_dict.fromkeys(abcdef)
-
{'a': None, 'b': None, 'c': None, 'd': None, 'e': None, 'f': None}
-
- my_dict.fromkeys(‘abcdef’, 5)
- {'a': 5, 'b': 5, 'c': 5, 'd': 5, 'e': 5, 'f': 5}
Just a bit about defaultdict
Additionally, once good solution to resolve defaultdict issues is to make sure that it targets a simple function. Like this:
1 2 3 4 5 6 7 |
from collections import defaultdict def default_dict_result(): return 'No such value in the dictionary, sorry.' my_new_dict = defaultdict(default_dict_result) print(my_new_dict['Germany']) |
What if we need to not care about strings and integers in a dictionary?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
# Code is from EXERCISE 42 - FlexibleDict - Python Workout - Author Lerner - Manning # https://www.manning.com/books/python-workout class FlexibleDict(dict): def __getitem__(self, key): try: if key in self: pass elif str(key) in self: key = str(key) print('in the dictionary it is a str!') elif int(key) in self: key = int(key) print('in the dictionary it is a int!') except ValueError: pass return dict.__getitem__(self, key) |
The idea here, is that in general, this will work as a normal dictionary. Unless you are looking for [‘1’] and the only present key is [1]. Or the other way around. Then this dictionary implementation would save you some seconds of debugging. And would probably create hours of debugging later, but who knows…
The YouTube video is this one: