A function returns two lists which are logically mapped one-to-one. Suppose
name = ["facebook", "twitter", "myspace"]
hits = [4000, 2500, 1800]
Therefore, hits for facebook are 4000, twitter 2500, and myspace 2500.
I want to convert these two separate lists into a list of dictionaries like
[
{name: 'facebook',data: [4000]},
{name: 'twitter',data: [2500]},
{name: 'myspace',data: [1800]}
]
My solution to do this is:
data = [
{"name":l, "data":[v]}
for idx1, l in enumerate(labels)
for idx2, v in enumerate(values)
if idx1 == idx2
]
Is there a more elegant way of dealing with logical one-to-one mapping or is my solution precise?
You could do:
[{"name": n, "data": [h]} for n, h in zip(name, hits)]
While this does what you asked for, there's probably more data structure here than you really need. Consider:
>>> dict(zip(name, hits))
{'twitter': 2500, 'myspace': 1800, 'facebook': 4000}
This provides the same data set in an easier-to-access data structure.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With