I am newbie to Python and need to convert a list to dictionary. I know that we can convert a list of tuples to a dictionary.
This is the input list:
L = [1,term1, 3, term2, x, term3,... z, termN]
and I want to convert this list to a list of tuples (or directly to a dictionary) like this:
[(1, term1), (3, term2), (x, term3), ...(z, termN)]
How can we do that easily in Python?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
>>> L = [1, "term1", 3, "term2", 4, "term3", 5, "termN"] # Create an iterator >>> it = iter(L) # zip the iterator with itself >>> zip(it, it) [(1, 'term1'), (3, 'term2'), (4, 'term3'), (5, 'termN')]
You want to group three items at a time?
>>> zip(it, it, it)
You want to group N items at a time?
# Create N copies of the same iterator it = [iter(L)] * N # Unpack the copies of the iterator, and pass them as parameters to zip >>> zip(*it)
Method 2
Try with the group clustering idiom:
zip(*[iter(L)]*2)
From https://docs.python.org/2/library/functions.html:
The left-to-right evaluation order of the iterables is guaranteed.
This makes possible an idiom for clustering a data series into
n-length groups using zip(*[iter(s)]*n).
Method 3
List directly into a dictionary using zip to pair consecutive even and odd elements:
m = [ 1, 2, 3, 4, 5, 6, 7, 8 ]
d = { x : y for x, y in zip(m[::2], m[1::2]) }
or, since you are familiar with the tuple -> dict direction:
d = dict(t for t in zip(m[::2], m[1::2]))
even:
d = dict(zip(m[::2], m[1::2]))
Method 4
Using slicing?
L = [1, "term1", 2, "term2", 3, "term3"] L = zip(L[::2], L[1::2]) print L
Method 5
[(L[i], L[i+1]) for i in xrange(0, len(L), 2)]
Method 6
Try this ,
>>> L = [1, "term1", 3, "term2", 4, "term3", 5, "termN"] >>> it = iter(L) >>> [(x, next(it)) for x in it ] [(1, 'term1'), (3, 'term2'), (4, 'term3'), (5, 'termN')] >>>
OR
>>> L = [1, "term1", 3, "term2", 4, "term3", 5, "termN"] >>> [i for i in zip(*[iter(L)]*2)] [(1, 'term1'), (3, 'term2'), (4, 'term3'), (5, 'termN')]
OR
>>> L = [1, "term1", 3, "term2", 4, "term3", 5, "termN"] >>> map(None,*[iter(L)]*2) [(1, 'term1'), (3, 'term2'), (4, 'term3'), (5, 'termN')] >>>
Method 7
The below code will take care of both even and odd sized list :
[set(L[i:i+2]) for i in range(0, len(L),2)]
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0