A problem that I am facing on Python Dictionaries

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

    A problem that I am facing on Python Dictionaries

    I input the following:
    >>> collection={} #Initiate an empty dictionary
    >>>collection={ 'a':'first', 'a':'second','d ':'third','b':' fourth','e':'fi fth','b':'sixth '}
    >>> collection
    {'a':'second',' b':'sixth','e': 'fifth','d':'th ird'}

    Now my question is:

    Why does the output not include all the values (2 values for 'a' AND 2 values for 'b) BUT only shows the output of ONLY the second value for both these keys ('a' and 'b') that I have entered ?

    Is the reason be that the values of the keys - 'a' and 'b' are rewritten for the second values that I subsequently have entered ?

    Would appreciate your thoughts and comments.

    Regards,
    Sudip Bhattacharya
    **email address removed**
    Last edited by bvdet; Feb 20 '10, 01:45 PM. Reason: Removed email address
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Please do not post your email address. This is for your protection. See our posting guidelines here.

    BV - Moderator

    Comment

    • bvdet
      Recognized Expert Specialist
      • Oct 2006
      • 2851

      #3
      Dictionaries are Python's only built-in mapping type object. A mapping type object represents an arbitrary collection of objects that are indexed by another collection of almost arbitrary key values. In your example, you actually defined your dictionary twice.
      Code:
       #Initiate an empty dictionary
      collection={}
      # Instead of the next line
      # collection={'a':'first', 'a':'second','d':'third','b':'fourth','e':'fifth', 'b':'sixth'}
      collection['a']='first'
      When you have two of the same key values, the second definition is kept because a dictionary is mutable.

      You cannot have two entries in a dictionary with the same key value. If you must have multiple objects indexed by the same key, use a list to contain the objects as in:
      Code:
      dd['a'] = ['first', 'second']
      A good way to assign multiple items to a dictionary key through iteration is to use dictionary method setdefault(). Example:
      Code:
      >>> listoflists = [['a', 'first'], ['b', 'second'], ['a', 'next'], ['c', 'third'], ['b', 'last']]
      >>> dd = {}
      >>> for item in listoflists:
      ... 	dd.setdefault(item[0], []).append(item[1])
      ... 	
      >>> dd
      {'a': ['first', 'next'], 'c': ['third'], 'b': ['second', 'last']}
      >>>

      Comment

      • sudipb
        New Member
        • Jan 2010
        • 3

        #4
        Hey Thanks a ton !!!

        Your answer's been very helpful.

        A couple of clarifications that you could perhaps help me with:

        You mentioned:
        >>>for item in listoflists:
        ... dd.setdefault(i tem[0], []).append(item[1])

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

        That would be really smart :)

        Thanks,
        Sudip

        Comment

        • bvdet
          Recognized Expert Specialist
          • Oct 2006
          • 2851

          #5
          sudipb,

          Code:
          >>>for item in listoflists:
          ... dd.setdefault(item[0], []).append(item[1])
          item[0] in line 2 above is the dictionary key ('a', 'b', or 'c' in the example). If the key is not in the dictionary, assign the dictionary key to an empty list. Then the dictionary value is appended to the list. Another useful dictionary method is get(). Example:
          Code:
          >>> dd = {}
          >>> dd['b'] = 1
          >>> dd['c'] = 2
          >>> for letter in ['a','b','c','a','d','e','c','b','c']:
          ... 	dd[letter] = dd.get(letter, 0) + 1
          ... 	
          >>> dd
          {'a': 2, 'c': 5, 'b': 3, 'e': 1, 'd': 1}
          >>>
          In the example, we are counting the occurrences of letters in a list and storing the results in an existing dictionary that already stored some previous results (it also could be empty). This is how get() works: If letter is in the dictionary, return its value, otherwise return 0. We add the returned value to 1 and assign the result to the key.

          Comment

          Working...