Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Feb 2011
    Thanked 0 Times in 0 Posts

    Smile Need some help understanding.

    I just started learning python 3 a week ago and have come by this snippet in my learning and cannot understand where the 'K' object comes from as it hasn't been defined. In the tutorial it doesn't explain this. I know this might seem like a dumb question but i really would like to know what's going on:

    def main():
        d = dict(
                 one = 1, two = 2, three = 3, four = 4, five = 5
        d['seven'] = 7
        for k in sorted(d.keys()):
            print(k, d[k])
    if __name__ == "__main__": main()
    Hope someone can explain it simply, ty.

  2. #2
    Senior Coder
    Join Date
    Jul 2011
    Thanked 171 Times in 171 Posts
    k is being defined in the for loop. for k in d.keys() means k is assigned to the value of d.keys() for every single key in the d dictionary. Output of that should be something like "one 1 two 2.." etc.


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts