Search code examples
pythondictionarysetcompound-assignment

python / sets / dictionary / initialization


Can someone explain help me understand how the this bit of code works? Particularly how the myHeap assignment works. I know the freq variable is assigned as a dictionary. But what about my myHeap? is it a Set?

    exe_Data = {
      'e' : 0.124167,
      't' : 0.0969225,
      'a' : 0.0820011,
      'i' : 0.0768052,
     }

    freq = exe_Data)

    myHeap = [[pct, [symbol, ""]] for symbol, pct in freq.items()]

Solution

  • exe_Data = {
      'e' : 0.124167,
      't' : 0.0969225,
      'a' : 0.0820011,
      'i' : 0.0768052,
     }
    

    The above code creates a dictionary called 'exe_Data'. Another way to do this is to use the built-in constructor, dict() with keyword arguments as follows: exe_Data = dict(e=0.12467, t=0.0969225, a=0.0820011, i=0.0768052)

    freq = exe_Data)
    

    I think the above bit should read freq=exe_Data. It makes another reference to the dictionary created in the previous bit.

    myHeap = [[pct, [symbol, ""]] for symbol, pct in freq.items()]
    

    This last part creates a list using a list comprehension. It creates a list of lists of two things, The first thing is a key from the dictionary created and referenced above, and the second thing is a list containing the corresponding value from the dictionary and a blank string.

    EDIT: In answer to the comment, it would be the equivalent of writing:

    myHeap = []
    for key, val in freq.items():
        myHeap.append([key, [val, ""]])