Converting a Python list into a dictionary while specifying certain elements as keys and values

Viewed 57

I have the below list called My_list and want to convert it to a dictionary called My_dict.

My_list=['I=113','PLAN=1','A=0PDFGB','B=23FGC','C=26TGFGD','D=19TGE','E=18TGA',
         'I=120','PLAN=2','A=0PDFGB','B=23FGC','C=26TGFGD','D=19TGE','E=18TGA']

the output should be as below:

My_dict={'I=113': ['PLAN=1', 'A=0PDFGB', 'B=23FGC', 'C=26TGFGD','D=19TGE', 'E=18TGA'],
         'I=120': ['PLAN=2', 'A=0PDFGB', 'B=23FGC',' C=26TGFGD','D=19TGE','E=18TGA']}

As you see, I want to make the strings starting with I= become my dictionary's keys and the ones between two strings that start with I= to be my first keys values, and so on.

I'd appreciate your guidance on this matter.

3 Answers

We could use a loop:

out = {}
for item in My_list:
    if item.startswith('I'):
        out[item] = []
        current = item
    else:
        out[current].append(item)

Output:

{'I=113': ['PLAN=1', 'A=0PDFGB', 'B=23FGC', 'C=26TGFGD', 'D=19TGE', 'E=18TGA'],
 'I=120': ['PLAN=2', 'A=0PDFGB', 'B=23FGC', 'C=26TGFGD', 'D=19TGE', 'E=18TGA']}

Write a loop that keep track of the current key and its associated values. Then, when we see a new key, add the existing key and value to the dictionary.

data = ['I=113','PLAN=1','A=0PDFGB','B=23FGC','C=26TGFGD','D=19TGE','E=18TGA', 'I=120', 'PLAN=2', 'A=0PDFGB', 'B=23FGC', 'C=26TGFGD', 'D=19TGE', 'E=18TGA']

result = {}
current_list = None
current_key = None

for item in data:
    if item.startswith('I='):
        if current_key is not None:
            result[current_key] = current_list
        current_list = []
        current_key = item
    elif current_key is not None:
        current_list.append(item)

if current_key is not None:
    result[current_key] = current_list
    
print(result)

This prints:

{'I=113': ['PLAN=1', 'A=0PDFGB', 'B=23FGC', 'C=26TGFGD', 'D=19TGE', 'E=18TGA'],
'I=120': ['PLAN=2', 'A=0PDFGB', 'B=23FGC', 'C=26TGFGD', 'D=19TGE', 'E=18TGA']}

You can use enumerate and zip

data =['I=113','PLAN=1','A=0PDFGB','B=23FGC','C=26TGFGD','D=19TGE','E=18TGA',
         'I=120','PLAN=2','A=0PDFGB','B=23FGC','C=26TGFGD','D=19TGE','E=18TGA']


index_list = [idx for idx, item in enumerate(data) if item.startswith('I')]
res = {data[start]: data[start + 1: end] for start, end in zip(index_list, index_list[1:]+[len(data)])}
print(res)

Output:

{'I=113': ['PLAN=1', 'A=0PDFGB', 'B=23FGC', 'C=26TGFGD', 'D=19TGE', 'E=18TGA'],
 'I=120': ['PLAN=2', 'A=0PDFGB', 'B=23FGC', 'C=26TGFGD', 'D=19TGE', 'E=18TGA']}
Related