Home > Software engineering >  List elements to dictionary based on condition
List elements to dictionary based on condition

Time:11-17

I have a list that has the keys and values of a dictionary as elements. I want to change it into a dictionary. Any help would be appreciated. I am new to programming.

List=[key1,key2,value2,value2,key3,value3,value3,key4,value4]

I want to change it into:

dict={key1:[],key2:[value2,value2],key3:[value3,value3],key4:[value4]}

The approach would be:

Loop through the lists and recognize the keys and add the next elements to the key until we hit the next key.

For example key1 is empty because before encountering any values we hit the next key (key2). Of course, you can use other approaches if you prefer.

CodePudding user response:

You must take elements from the initial list one at a time. If an element has the 'key' string inside it, then add a new item to the dictionary with an empty list as value, and retain that current list. Else, add the element to the current list. Possible code:

lst = ['key1', 'key2', 'value2', 'value2', 'key3', 'value3', 'value3', 'key4', 'value4']
d = dict()
l = []
for elt in lst:
    if 'key' in elt:
        l = []
        d[elt] = l
    else:
        l.append(elt)

I gives as expected:

{'key1': [], 'key2': ['value2', 'value2'], 'key3': ['value3', 'value3'], 'key4': ['value4']}

Beware: above code would silently discard any value preceding the first key...

CodePudding user response:

Curious choice of example, but IIUC you're aiming at something like this.

list_in = ["key1","key2","value2","value2","key3","value3","value3","key4","value4"]
dict_out = {}

curr_key = None
for el in list_in:
  if "key" in el: # replace with your actual condition
    dict_out[el] = []
    curr_key = el
  else:
    dict_out[curr_key].append(el)

print(dict_out)

Output:

{'key1': [], 'key2': ['value2', 'value2'], 'key3': ['value3', 'value3'], 'key4': ['value4']}
  • Related