Home > front end >  How to loop through list and assign some variables as a key and some as a value?
How to loop through list and assign some variables as a key and some as a value?

Time:05-03

Hellooo,

I'm having a hard time trying to figure out how to loop through a list and assign some as keys and some as values. I've searched through Stack Overflow for awhile now and couldn't find a question quite like this so I'm posting.

Here's the situation:

my_list = ['start_here', 'a1', 'b2', 'a3', 'start_here_2', 'b1', 'a2', 'start_here_3', 'a1', 'b2', 'a3', 'b4']

(and it could continue to start_here_4, start_here_5, etc with any number of a# or b#s)

And here's my desired output:

my_dict = {'start_here': ['a1', 'b2', 'a3'], 'start_here_2': ['b1', 'a2'], 'start_here_3': ['a1', 'b2', 'a3', 'b4']

I don't know if I should split my original list into 3 or 4 or however many and then make index 0 the key, followed by a list of the variables remaining as the value or if there's a way to bypass that and create a dictionary from the original list immediately.

Thank you in advance, I'm a bit new!

CodePudding user response:

Like this, for example:

my_list = ['start_here', 'a1', 'b2', 'a3', 'start_here_2', 'b1', 'a2', 'start_here_3', 'a1', 'b2', 'a3', 'b4']
key = None
my_dict = {}
for v in my_list:
    if v.find('start_here') == 0:
        key = v
        my_dict[key] = []
    else:
        my_dict[key].append(v)
print(my_dict)

Output:

{'start_here': ['a1', 'b2', 'a3'], 'start_here_2': ['b1', 'a2'], 'start_here_3': ['a1', 'b2', 'a3', 'b4']}

The find method identifies each list element beginning with start_here, saves that element as the new key and adds an entry to my_dict with that key and with an empty list as the value, then appends subsequent list elements to that key's list value until the next key (namely, the next list element beginning with start_here) is encountered.

UPDATE: Alternatives to using find() (probably superior) are shown below.

(1) Assuming any string in the list beginning with start_here is to be treated as a key (credit to @Jasmijn in a comment):

key = None
my_dict = {}
for v in my_list:
    if v.startswith('start_here'):
        key = v
        my_dict[key] = []
    else:
        my_dict[key].append(v)

(2) Assuming any string in the list containing start_here as a substring is to be treated as a key:

key = None
my_dict = {}
for v in my_list:
    if 'start_here' in v:
        key = v
        my_dict[key] = []
    else:
        my_dict[key].append(v)
  • Related