Harry Tormey

October 11, 2009

Random Tech Nugget: Creating a dictionary from a list in Python

Filed under: Programming, Python — Tags: — admin @ 5:05 pm
Say you have a list and you want to create a dictionary such that the contents of the list become the keys of the dictionary. This is how you would do it:

 Python |  copy code |? 
1
#Example, key = file name in list, value = path+filename
2
import os
3
path      = os.path.abspath(os.path.dirname(__file__))
4
mylist   = ['harry.png', 'andy.png', 'dan.png']
5
aDict    = dict([(fn, os.path.join(path, fn)) for fn in mylist])

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment

Powered by WordPress