I have trouble converting the nested list into dictionaries.
For example nested list with [[5, 0], [6, 0], [7, 1, 0], [8, 1, 0], [9, 1]]
. I hope to get a result of
{5:[0], 6:[0], 0:[5,6,7,8,1], 1:[7,8,9], 7:[1,0], 8:[1,0], 9:[1]}
I have tried method such as using nested for loop and list comprehension but can't achieve the above solution.
Is there any way that I can achieve such results?
Imo, you're looking for permutations which are implemented in itertools
:
from collections import defaultdict
from itertools import permutations
lst = [[5, 0], [6, 0], [7, 1, 0], [8, 1, 0], [9, 1]]
dd = defaultdict(set)
for sublst in lst:
for key, value in permutations(sublst, 2):
dd[key].add(value)
print(dd)
This yields
defaultdict(<class 'set'>, {5: {0}, 0: {1, 5, 6, 7, 8}, 6: {0}, 7: {0, 1},
1: {0, 8, 9, 7}, 8: {0, 1}, 9: {1}})
I managed to make this but the complexity of the algorithm is O(n^3). May be there is a way to do it with a lower complexity but I didn't find how to.
mylist = [[5, 0], [6, 0], [7, 1, 0], [8, 1, 0], [9, 1]]
dictionnary = {}
for l in mylist:
# For each list, select one element and iterate through all
# the list's elements in order to populate the dict.
for currentElem in l:
for otherElem in l:
if currentElem != otherElem:
# create the key and empty list if not exists
if currentElem not in dictionnary.keys():
dictionnary[currentElem] = []
# add value to key only if not already there
if otherElem not in dictionnary[currentElem]:
dictionnary[currentElem].append(otherElem)
print(dictionnary)
Generated output:
{5: [0], 0: [5, 6, 7, 1, 8], 6: [0], 7: [1, 0], 1: [7, 0, 8, 9], 8: [1, 0], 9: [1]}
This is pretty much what you want except for the key 1
. Either it's a typo in your post or I didn't managed to do what you want.
My algorithm produces sorted output, both dict keys and list-values are sorted.
Algorithm complexity is O(N * M)
where N is total count of numbers and M is the average sub-list length.
def to_dict(l):
d = {}
for e0 in l:
s = set(e0)
for e1 in s:
if e1 not in d:
d[e1] = set()
d[e1].update(s - {e1})
return dict(sorted([(k, sorted(v)) for k, v in d.items()]))
print(to_dict([[5, 0], [6, 0], [7, 1, 0], [8, 1, 0], [9, 1]]))
Output:
{0: [1, 5, 6, 7, 8], 1: [0, 7, 8, 9], 5: [0], 6: [0], 7: [0, 1], 8: [0, 1], 9: [1]}
arr = [[5, 0], [6, 0], [7, 1, 0], [8, 1, 0], [9, 1]]
my_dict = {}
for i in arr:
for j in range(len(i)):
if i[j] in my_dict.keys():
temp = set(i[:j] + i[j+1:])
temp_2 = set(my_dict[i[j]])
new_temp = temp - temp_2
my_dict[i[j]] += new_temp
else:
my_dict[i[j]] = i[:j] + i[j+1:]
print(my_dict)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.