Python Loops: The Exact Way to Handle Map Mappings

The function returns two lists that are logically displayed one to one . Let be

name = ["facebook", "twitter", "myspace"] hits = [4000, 2500, 1800] 

Thus, the hits for facebook are 4000, twitter 2500 and myspace 2500.

I want to convert these two separate lists to a list of dictionaries , for example

 [ {name: 'facebook',data: [4000]}, {name: 'twitter',data: [2500]}, {name: 'myspace',data: [1800]} ] 

My solution for this:

 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 to deal with one-to-one logical matching, or is my exact solution?

+4
source share
3 answers

You can do:

 [{"name": n, "data": [h]} for n, h in zip(name, hits)] 

As long as this does what you requested, there is probably more data structure 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.

+13
source

The easiest and fastest way to handle one-to-one relationships is to create two dictionaries:

 >>> name = ["facebook", "twitter", "myspace"] >>> hits = [4000, 2500, 1800] >>> name2hits = dict(zip(name, hits)) >>> hit2name = dict(zip(hits, name)) 
+4
source

Similar but not quite the same as Effective bidirectional hash table in Python?

You should just use two dictionaries, and when you do the update, apply the update to both.

In addition, there is a logical inconsistency: either your function is not individual, or you do not need to store data: [...] in the list, since there can only be one value.

If you really need to convert it to a list of dictionaries, use zip as indicated in fooobar.com/questions/1387520 / ...

0
source

Source: https://habr.com/ru/post/1387520/


All Articles