Home > database >  Converting a python list into a dictionary while specifying certain elements as keys and values
Converting a python list into a dictionary while specifying certain elements as keys and values

Time:03-01

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'll appreciate your guidance on this matter.

CodePudding user response:

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

CodePudding user response:

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']}
  • Related