简体   繁体   中英

How does this for-loop within this dictionary work exactly?

Currently I'm learning Python text sentiment module via this online course and the lecturer failed to explain in enough detail how this piece of code works. I tried searching each piece of code individually to try piece together how he did it but it makes no sense to me.

  1. So how does this code work? Why is there a for loop within dictionary braces?

  2. What is the logic behind x before the for y in emotion_dict.values() then for x in y at the end?

  3. What is the purpose behind emotion_dict=emotion_dict within the parentheses? Wouldn't just emotion_dict do?

      def emotion_analyzer(text,emotion_dict=emotion_dict): #Set up the result dictionary emotions = {x for y in emotion_dict.values() for x in y} emotion_count = dict() for emotion in emotions: emotion_count[emotion] = 0 #Analyze the text and normalize by total number of words total_words = len(text.split()) for word in text.split(): if emotion_dict.get(word): for emotion in emotion_dict.get(word): emotion_count[emotion] += 1/len(text.split()) return emotion_count 

1 and 2

The line emotions = {x for y in emotion_dict.values() for x in y} uses a set comprehension . It builds a set, not a dictionary (though dictionary comprehensions also exist and look somewhat similar). It is shorthand notation for

emotions = set()  # Empty set
# Loop over all values (not keys) in the pre-existing dictionary emotion_dict
for y in emotion_dict.values():
    # The values y are some kind of container.
    # Loop over each element in these containers.
    for x in y:
        # Add x to the set
        emotions.add(x)

The x right after the { in the original set comprehension signifies which value to store in the set. In all, emotions is just a set (with no repeats) of all elements within all containers within the dictionary emotion_dict . Try printing out emotion_dict and emotion and compare.

3

In the function definition,

def emotion_analyzer(text, emotion_dict=emotion_dict):

the emotion_dict=emotion_dict means that the local variable with name emotion_dict gets set to the global variable similarly named emotion_dict , if you do not pass anything as the second argument. This is an example of a default argument .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM