To comprehend the dictionary created inside the understanding of the dictionary

I have a number dictionary for lists of numbers like:

a = {1: [2,3,4], 2: [1,4]}

I want to create a new dictionary with understanding on it, where each element from each list will be associated with the key of this list.

It will be something like:

b = {element: [key] for the key in a.keys () for the element in [key]}

which gives me of course:

b = {1: [2], 2: [1], 3: [1], 4: [2]}

instead

b = {1: [2], 2: [1], 3: [1], 4: [1,2]}

because the index is overwritten. so i need to do something like:

b = { element : [key] + self[element] for key in a.keys() for element in a[key]} 

or

 b = { element +: key for key in a.keys() for element in a[key]} 

but in working condition.

Is it possible?

+4
source share
3 answers

im suggesting that this is for some form of mapping:

 from itertools import chain def makeMap(d): nodes = set([x for x in chain.from_iterable(d.values())]) return dict([[x, [y for y in d.keys() if x in d[y]]] for x in nodes ]) 

this code will do it for you :)


EDIT:

and heres (massive) one liner, I would not recommend putting this in code, though, since it is unreadable.

 def makeMap(d): return dict([[x, [y for y in d.keys() if x in d[y]]] for x in set([x for x in chain.from_iterable(d.values())]) ]) 

Steps:
1. make a set of all possible node values ​​2. Find all node values ​​in dictionary values, if you put the key that he found in the matching list.

+2
source

It is easy to build a dictionary using defaultdict and two loops.

 from collections import defaultdict a = { 1: [2,3,4] , 2: [1,4] } b = defaultdict(list) for key, value in a.iteritems(): for elem in value: b[elem].append(key) 
+3
source

Everything is possible:

 >>> a = { 1: [2,3,4] , 2: [1,4] } >>> d={} >>> for k, v in sum(map(lambda x: zip(x[1], [x[0]]*len(x[1])), a.items()), []): ... d.setdefault(k, []).append(v) ... >>> d {1: [2], 2: [1], 3: [1], 4: [1, 2]} >>> 
+2
source

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


All Articles