I have a list string_array = ['1', '2', '3', '4', '5', '6']
and a list of lists
multi_list = [['1', '2'], ['2', '3'], ['2', '4'], ['4', '5'], ['5', '6']]
The first element of each sub-list in multi_list
will have an associated entry in string_array
.
(Sublists will not have duplicate elements)
How do I map these associated elements into a dictionary like:
{
'1': ['2'],
'2': ['3', '4'],
'3': [],
'4': ['5'],
'5': ['6'],
'6': []
}
Here's a few concepts that will help you, but I'm not going to give you the complete solution. You should do so on your own to sink in the concepts.
To make an empty dictionary of lists
{'1': [],'2': [],'3': [],'4': [],'5': [],'6': [],
}
you can use a for loop:
list_one = ['1', '2', '3', '4', '5', '6']my_dict = {}
for value in list_one:my_dict[value] = []
You could also get fancy and use a dictionary comprehension:
my_dict = {value: [] for value in list_one}
Now you'll need to loop over the second list and append
to the current list. e.g. to append to a list you can do so in a few ways:
a = [1,2]
b = [3,4]
c = 5# add a list to a list
a += b
# now a = [1,2,3,4]# add a list to a list
b.append(c)
# now b = [3,4,5]
To chop up lists you can use slice notation:
a = [1,2,3,4]
b = a[:2]
c = a[2:]
# now b = [1,2], and c = [3,4]
And to access an item in a dictionary, you can do so like this:
a = { '1': [1,2,3] }
a['1'] += [4,5,6]
# now a = { '1': [1,2,3,4,5,6] }