Melissa Stewart Melissa Stewart - 2 months ago 13
Python Question

Idiomatic Python iterating and adding to a dict

I'm running through a string, creating all substrings of size 10, and adding them to a dict. This is my code,

sequence_map = {}
for i in range(len(s)):
sub = s[i:i+10]
if sub in sequence_map:
sequence_map[sub] += 1
else:
sequence_map[sub] = 1


Is there a way to do this more pythonically?

Also how do I do the reverse pythonically, as in interating through the dict and composing a list where value is equal to something?

[k for k, v in sequence_map.items()]

DYZ DYZ
Answer Source

You can use a defaultdict which is "smart" enough to add missing keys as needed:

from collections import defaultdict
sequence_map = defaultdict(int)
for i in range(len(s) - 10):
    sub = s[i:i + 10]
    sequence_map[sub] += 1

As for the second part of your question, are you looking for this?

[k for k, v in sequence_map.items() if v==something]