Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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': []
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
152 views
Welcome To Ask or Share your Answers For Others

1 Answer

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] }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...