Question:

Turn A List Into A Dictionary.

Answer:

In a dictionary, each item represents a key-value pair. So converting a list isn’t as straight forward as it were for other data types.

However, we can achieve the conversion by breaking the list into a set of pairs and then call the <zip()> function to return them as tuples.

Passing the tuples into the <dict()> function would finally turn them into a dictionary.

Example

weekdays = ['sun','mon','tue','wed','thu','fri']
listAsDict = dict(zip(weekdays[0::2], weekdays[1::2]))
print(listAsDict)
#output: {'sun': 'mon', 'thu': 'fri', 'tue': 'wed'}

 


Keywords:

© 2017 QuizBucket.org