list(tags.keys())
Hey, I wanted to ask why you use list(%some_dictionary%.keys()), for example:
for key in list(tags.keys()):
for key in list(tags.keys()):
As far as I'm concerned, you can iterate over keys or values without list()-ing them. Sorry if it's a stupid question, I'm just learning Python.
Hey! @demidovakatya
Actually, It's not a stupid question at all. And you're right in that you can directly iterate over values without explicitly building a list.
Python doesn't allow you to modify a dictionary while iterating it, so rather than iterating over keys of a dictionary, i build a separate list of keys, and iterate over them instead.
If I would've iterated over the keys directly, this line would've resulted in an error, since it modifies the dictionary.
Hope I made it clear :)
Okay, this is how I've translated your code:
for key in list(tags.keys()):
# by THIS KEY I mean: key in this iteration
# if frames exists and this key isn't in frames
if ((frames and key not in frames)
# if frames_skip exists and key is in frames_skip
or (frames_skip and key in frames_skip)
# if this key's value (tags[key]) is not a TextFrame
or not isinstance(tags[key], TextFrame)):
# screw it
continue
# if this pattern is in this key's value
if re.search(pattern, str(tags[key])):
# replace pattern with some stuff
sub = re.sub(pattern, repl, str(tags[key]))
# make it a list and put it into this key's value
tags[key].text = [sub]
# but if sub is False and prune is true
if not sub and prune:
# screw this key and its value
del tags[key]
Now, I don't understand even more things:
- to begin with, you CAN modify dictionaries. You shouldn't do it in a loop link, though;
- when
if not sub and pruneis false? -
tags[key].text = [sub]- why do you make it? -
if re.search(pattern, str(tags[key]))- what would change if we removed this line?
Thank for your previous answer, I hope my questions would be useful for you as well. :)