Python:Query on Conditional Loops and the setdefault method

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sudipb
    New Member
    • Jan 2010
    • 3

    Python:Query on Conditional Loops and the setdefault method

    >>>listoflist s = [['a', 'first'], ['b', 'second'], ['a', 'next'], ['c', 'third'], ['b', 'last']]
    >>> dd = {}
    >>>for item in listoflists:
    ... dd.setdefault(i tem[0], []).append(item)

    - The part which mentions 'item[0]' would be to have the first letter of each item in the list we created right ?
    - what does the ' [ ] ' signify in this case ? Does it mean to have a null value for each key that we create for the dictionary and add/create the value associated with the key from the append method ?

    Regards,
    Sudip Bhattacharya
  • Motoma
    Recognized Expert Specialist
    • Jan 2007
    • 3236

    #2
    You are correct, in this case, item[0] represents 'a', 'b', or 'c'.

    [] signifies an empty list. If you look at the documentation for setdefault, it will return a the value of the dictionary element specified in the first argument, or, if it has no value, it will return the second argument.

    Comment

    Working...