Tuesday, July 23, 2013

Make dictionary out of two lists

Problem : Now that we have two lists - One list of keys and other list of values and we want to make dictionary out of this. How to do this using Python

Solution : Use zip command to merge the two lists. If the list count is not equal the zip command will truncate the longer one. So I will try to put a length check before merging.

So if keyList and valueList are the two lists we need to merge and make dictionary , lets make one :


newDict ={}
if len(keyList) == len(valList):
    newDict = dict(zip(keyList,valList))

And we are good to go :)

No comments:

Post a Comment