Python Forum
Appending to a list in the right order
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Appending to a list in the right order
#1
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.
Reply
#2
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)
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
I got it to work by switching line 1 and 2. Not sure why though, but thank you for the answer!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  sorting a list using unicodes acending order, no loops, no sort(), using recursion lrn2codee 14 6,357 Jun-23-2021, 07:33 PM
Last Post: deanhystad
  Multiplying number in a list in an order pythoneer 12 6,564 Mar-23-2018, 08:21 PM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020