Python Dictionary – Advanced. With YouTube video.

Some time ago, I wrote an article about defaultdict  in Python here – 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.

A horse from the mine museum of Pernik, Bulgaria

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)
  • 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:

What if we need to not care about strings and integers in a dictionary?

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: