How to create a dictionary using 2 lists?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Harsh Hajela

    How to create a dictionary using 2 lists?

    I've 2 lists say:
    Code:
    list1 = ['a','b','c']
    list2 = [1,2,3]
    and i want a dictionary as an output:
    Code:
    dict1 = {'a':1,'b':2,'c':3}
    How to achieve this using Built in Functions?
    Last edited by Frinavale; Oct 7 '10, 05:12 PM. Reason: Please post code in [code] ... [/code] tags. Added code tags.
  • Frinavale
    Recognized Expert Expert
    • Oct 2006
    • 9749

    #2
    Why not just loop through each list and set the dictionary values?

    For example:
    (pseudo code)
    Code:
    Loop through List1 and List2
      For this iteration get the Key from List1
      For this iteration get the Value from List2
      Add an item to the dictionary at the Key with the Value for this iteration
    Increment the iteration and go back to the start of the loop
    -Frinny

    Comment

    • Harsh Hajela

      #3
      Thanks mate for your reply..

      i was looking for some built in function.. i faced an interview today and i was clueless when they asked me to use built in functions of python..

      Comment

      • bvdet
        Recognized Expert Specialist
        • Oct 2006
        • 2851

        #4
        Code:
        >>> dict(zip(['a','b','c'], [1,2,3]))
        {'a': 1, 'c': 3, 'b': 2}
        >>>

        Comment

        • Harsh Hajela

          #5
          Thanks mate..
          That works :)

          Comment

          Working...