Python Forum

Full Version: Appending to a list in the right order
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi everyone,

So I am basically trying to iterate over a list of 12 values and if a value at a specific index (every third) is also a value in a dictionary, I want to append that corresponding key to a new list. ps is a list with 12 values. dict is a dictionary also with 12 keys and values.

ps = [57.06, 98.74, 83.3, 77.24, 63.59, 101.11, 83.2, 90.67, 85.12, 72.28, 86.16, 92.56]
for key, value in dict.items():
      for count in range(0,10,3):
         if value == ps[count]:  
            list1.append(key)
So I want to append the keys to the values in list1 at indexes 0,3,6 and 9. This works but they are appended in random order it seems. So when I print the list1 I get values in the oder(6,0,3,9).Does anyone know if there is a way to make sure it gets appended rigth? Any help would be much appreciated.
Well, it's not clear why 0, 3, 6, 9 is the right order, so it's kind of hard to answer. Do you just want them sorted? If so just do list1.sort() at the end, after all of the loops.

If you want them in the order of the values in the list, you should sort on the list first. Also, you should iterate over the list, not the indexes of the list, as shown here. So maybe something like this:

for list_value in list1:
    for key, value in dict.items():
        if list_value = value:
            list1.append(key)
I got it to work by switching line 1 and 2. Not sure why though, but thank you for the answer!