|
|
Question : How to make a dictionary out of one list.
|
|
Let's say that I have a list that looks like this:
stuff = ["70", "seventy", "80", "eighty", "90", "ninety"]
How do I convert this into one dictionary in the form of:
dictionarystuff = { '70': 'seventy', '80': 'eighty', '90': 'ninety'}
Thanks, linuxio
|
Answer : How to make a dictionary out of one list.
|
|
From the Python Library reference - Built-in functions: (I edited out the alternatives not used above) " dict( ... sequence)
Return a new dictionary initialized from an argument .... the argument must be .... an iterator object. The elements of the argument must each [be a sequence], and each must in turn contain exactly two objects. The first is used as a key in the new dictionary, and the second as the key's value. "
(stuff[i:i+2] for i in range(0, len(stuff), 2)) is a "generator expression" which, in the context of the () of the dict function call, creates a "generator object" which in turn is a version of an "iterator object". It is roughly equivalent to:
for i in range(0, len(stuff), 2): yield stuff[i:i+2]
Out of this comes ["70", "seventy"] then ["80", "eighty"] finally ["90", "ninety"].
Is that enough, helpful, too much??
|
|
|
|
|