DEV Community

Alex Turner
Alex Turner

Posted on

Getting to grips with dictionary comprehensions.

I've given myself a much harder time learning dictionary comprehensions than necessary. Code block. Like writers block perhaps? Feeling a bit slow with being stuck for a while on a project stage.

A touch of cognitive overload. Some interesting ideas about this at Cognitive Load and Coding. Worth a read with some good references at the end to follow up. A progammers cognitve load was especially helpful. I have increased the font size in my IDE and enabled auto folding. Basic stuff I could have done ages ago if I'd have been curious enough.

Back pain. Change in routines blah blah blah... It's all transient so long as I don't give up. Take some respite and come back to the learning.

Made some progress yesterday. A new approach. Narrowed my focus. Completed some PyBites. Encouraged by solving a few of these I completed one on dictionary comprehensions. PyBites is handy to have on my list of go to places for learning Python.

I am hoping to help embed what I'm spending time learning by writing something about it here. First time trying. Hopefully I've understood it and I've written nothing that will misinform. Critique / corrections are welcome. Here goes:

bites = {6: 'PyBites Die Hard',
         7: 'Parsing dates from logs',
         9: 'Palindromes',
         10: 'Practice exceptions',
         11: 'Enrich a class with dunder methods',
         12: 'Write a user validation function',
         13: 'Convert dict in namedtuple/json',
         14: 'Generate a table of n sequences',
         15: 'Enumerate 2 sequences',
         16: 'Special PyBites date generator',
         17: 'Form teams from a group of friends',
         18: 'Find the most common word',
         19: 'Write a simple property',
         20: 'Write a context manager',
         21: 'Query a nested data structure'}
exclude_bites = {6, 10, 16, 18, 21}


def filter_bites(bites=bites, bites_done=exclude_bites):
    """return the bites dict with the exclude_bites filtered out"""
    return {key: value for (key, value) in bites.items() if key not in bites_done}


print(filter_bites(bites, exclude_bites))
Enter fullscreen mode Exit fullscreen mode

So what that does is to take a dictionary (bites) and a set (exclude_bites). From them we return a new dictionary from the entries of the existing dictionary excluding entries whose key matches an element in the set.

return {key: value for (key, value) in bites.items() if key not in bites_done}
Enter fullscreen mode Exit fullscreen mode

Which returns dictionary items -

{
7: 'Parsing dates from logs', 
9: 'Palindromes', 
11: 'Enrich a class with dunder methods', 
12: 'Write a user validation function', 
13: 'Convert dict in namedtuple/json', 
14: 'Generate a table of n sequences', 
15: 'Enumerate 2 sequences', 
17: 'Form teams from a group of friends', 
19: 'Write a simple property', 
20: 'Write a context manager'
}
Enter fullscreen mode Exit fullscreen mode

Notice that dictionary items with a key that matches an element in

exclude_bites = {6, 10, 16, 18, 21}

have been excluded.

Keys can be generated from an immutable type

int, float, decimal, complex, bool, string, tuple, range, frozenset, bytes

With this example the int is used (iterated) from the keys in bites dictionary. The keys must also be hashable. For example a tuple with lists will not work as lists are mutable and therefore not hashable. A tuple of strings would be fine as strings are immutable.

Python dictionaries leverage hash tables. When we use a key that contains an unhashable type, i.e. a list, the underlying hash map cannot guarantee the key will map to the same bucket every single time. If we can't hash our key, we can't use it in our dictionary. The thing to remember is that Python dictionaries require hashable dict keys. Immutable keys is not enough. (nods*)

The value may be assigned to any iterable bites_items() in this case. It does not need to be immutable. It could also be assigned the same value for all keys. The condition to filter/sort simply follows the if statement. Here th exclude_bites set is called to check and iterate through .

Well I think that worked. Feel like I have furthered by understanding a bit. Trying new ways of learning. Getting over stumbling blocks. Practice, do projects and don't give up!

Top comments (1)

Collapse
 
gravesli profile image
gravesli

I think you are great! i just want to discuss tech with Python developer.
I built a display machine state using Python3 with Flask!
Flask State Github:github.com/yoobool/flask-state
Should i can get some improvement suggestions from you? Thanks~