Create a key:value pair in the first loop and append more values in subsequent loops

Viewed 61

How can I create a key:value pair in a first loop and then just append values in subsequent loops? For example:

a = [1,2,3]
b = [8,9,10]
c = [4,6,5]

myList= [a,b,c]
positions= ['first_position', 'second_position', 'third_position']

I would like to create a dictionary which records the position values for each letter so:

mydict = {'first_position':[1,8,4], 'second_position':[2,9,6], 'third_position':[3,10,5]}

Imagine that instead of 3 letters with 3 values each, I had millions. How could I loop through each letter and:

  1. In the first loop create the key:value pair 'first_position':[1]
  2. In subsequent loops append values to the corresponding key: 'first_position':[1,8,4]

Thanks!

3 Answers

Try this code:

mydict = {}
for i in range(len(positions)):
    mydict[positions[i]] = [each[i] for each in myList]

Output:

{'first_position': [1, 8, 4],
 'second_position': [2, 9, 6],
 'third_position': [3, 10, 5]}

dictionary.get('key') will return None if the key doesn't exist. So, you can check if the value is None and then append it if it isn't.

dict = {}
for list in myList: 
  for position, val in enumerate(list):
    this_position = positions[position]
    if dict.get(this_position) is not None:
      dict[this_position].append(val)
    else:
      dict[this_position] = [val]

The zip function will iterate the i'th values of positions, a, b and c in order. So,

a = [1,2,3]
b = [8,9,10]
c = [4,6,5]

positions= ['first_position', 'second_position', 'third_position']
sources = [positions, a, b, c]

mydict = {vals[0]:vals[1:] for vals in zip(*sources)}
print(mydict)

This created tuples which is usually fine if the lists are read only. Otherwise do

mydict = {vals[0]:list(vals[1:]) for vals in zip(*sources)}
Related