I have two nested lists:
list1: [[1,2,3],[4,6],[44,77,86]]
list2: [[1,3],[4,6],[44,77,86],[65]]
How can I map them such that we will have each lists in those big two lists a key, which will be exactly the same key in the other lists?
dic1: [{0,[1,2,3]},{1,[4,6]},{2,[44,77,86]}]
dic1: [{4,[1,3]},{1,[4,6]},{2,[44,77,86]},{3,[65]}]
You can see that the two lists in the middle of each of the two big lists are the same - therefore, they have the same key in the dictionaries.
CodePudding user response:
dic1
is not a legal python object. but if you want to achieve the same logic:
First, let's give an index or every list in list1:
lookup_table = {}
for key, l in enumerate(list1):
lookup_table[tuple(l)] = key
# lookup_table = {(1, 2, 3): 0, (4, 6): 1, (44, 77, 86): 2}
Note that lookup_table is actually dic1.
Now, let's build dic2:
dict2 = {}
counter = len(list1)
for key, l in enumerate(list2):
if tuple(l) in lookup_table:
dict2[tuple(l)] = lookup_table[tuple(l)]
else:
dict2[tuple(l)] = counter
counter = 1
# dic2 = {(1, 3): 3, (4, 6): 1, (44, 77, 86): 2, (65,): 4}
I assume that if the list doesn't exists in list1, the key is some counter.
If you want to get the mapping in dictionary of lists, you can convert dic2:
dic2 = [{key: list(l)} for l, key in dict2.items()]
# dic2 = [{3: [1, 3]}, {1: [4, 6]}, {2: [44, 77, 86]}, {4: [65]}]
and the same for dic1.
CodePudding user response:
You don't need a lookup table. You can directly check the duplications with list1 :
list1 = [[1, 2, 3], [4, 6], [44, 77, 86]]
list2 = [[1, 3], [4, 6], [44, 77, 86], [65]]
dict1 = {}
for key, l in enumerate(list1):
dict1[key] = l
n = len(list1)
dict2 = {}
for l in list2:
if l in list1:
dict2[list1.index(l)] = l
else:
dict2[n] = l
n = 1
I think that's the simplest solution