Simple oneliner to built a dictionary from a list
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | """
The dict built-in function has many ways to build dictionaries but it cannot handle a sequence with alternating key and value pairs.
In python 2.3 it can be easily solved by combining dict, zip and extended slices.
"""
def DictFromList(myList):
return dict(zip(myList[:-1:2], myList[1::2]))
if __name__ == "__main__":
print DictFromList(["one", 1, "two", 2, "three", 3])
# prints: {'three': 3, 'two': 2, 'one': 1}
|
Tags: algorithms
Generator version. Consider factoring out the pairing logic into a generator. The result is fast, memory friendly, and works with any iterable.
Inline quote minimization method.