Looking for a way to transform a list of coordinates into pairs of dictionaries, ie if:
l = [1, 2, 3, 4, 5, 6, 7, 8]
I want to create a list of dictionaries:
output = [{'x': 1, 'y': 2}, {'x': 3, 'y': 4}, ... ]
Any ideas on how to do this "pythonically"?
The typical way is with the "grouper" recipe:
from itertools import izip
def grouper(iterable,n):
return izip(*[iter(iterable)]*n)
output = [{'x':a,'y':b} for a,b in grouper(l,2)]
The advantage here is that it will work with any iterable . The iterable does not need to be indexable or anything like that...
output = [{'x': l[i], 'y': l[i+1]} for i in range(0, len(l), 2)]
Or alternatively:
output = [{'x': x, 'y': y} for x, y in zip(*[iter(l)]*2)]
This method of grouping items from a list comes straight from the zip()
documentation .
You can do:
>>> mylist = [1,2,3,4,5,6,7,8]
>>> [{'x': x, 'y': y} for x, y in zip(mylist[::2], mylist[1::2])]
[{'y': 2, 'x': 1}, {'y': 4, 'x': 3}, {'y': 6, 'x': 5}, {'y': 8, 'x': 7}]
Note that dictionaries are unordered so {'y': 2, 'x': 1}
is the same as {'x': 1, 'y': 2}
. This makes use of Python's built-in zip()
function.
here's another way
>>> from itertools import izip
>>> l = [1, 2, 3, 4, 5, 6, 7, 8]
>>> l = iter(l)
>>> [dict(x=x, y=y) for (x, y) in izip(l, l)]
[{'y': 2, 'x': 1}, {'y': 4, 'x': 3}, {'y': 6, 'x': 5}, {'y': 8, 'x': 7}]
Or, as Lattyware suggests
>>> [{'x':x, 'y':y} for (x, y) in izip(l, l)]
[{'y': 2, 'x': 1}, {'y': 4, 'x': 3}, {'y': 6, 'x': 5}, {'y': 8, 'x': 7}]
I believe a namedtuple
would be more suited to this job than a dictionary. (Using itertools
grouper recipe like @mgilson)
>>> from collections import namedtuple
>>> from itertools import izip
>>> Point = namedtuple('Point', ('x', 'y'))
>>> def grouper(iterable,n):
return izip(*[iter(iterable)]*n)
>>> nums = [1, 2, 3, 4, 5, 6, 7, 8]
>>> [Point(x, y) for x, y in grouper(nums, 2)]
[Point(x=1, y=2), Point(x=3, y=4), Point(x=5, y=6), Point(x=7, y=8)]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.