Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python loops: Precise way to handle mapping matching lists

Tags:

python

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?

like image 798
Zain Khan Avatar asked Dec 04 '22 05:12

Zain Khan


1 Answers

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.

like image 200
Greg Hewgill Avatar answered Mar 03 '23 04:03

Greg Hewgill