简体   繁体   中英

Why are the values of my dictionary in the wrong order?

validSpeed = {"20" : "6", "30" : "14", "40" : "24", "50" : "38", "60" : "55", "70" : "75"}
speed = input("Enter the test speed> ")
if any(speed == key for key in validSpeed) :
  speedIndex = set(dist for dist in validSpeed.values())
  distance = input("Enter the stopping distance> ")
  if distance in speedIndex :
    print (speedIndex)

I only started python a few days ago so the code is probably really bad, but I want to match the speed to the stopping distance, but they will only match with different value.

speedIndex = set(dist for dist in validSpeed.values())

I used this bit of code from this site, and it creates this array sort of thing- {'38', '24', '55', '75', '14', '6'}, which is the complete wrong order than what I put them in the dictionary. I could just change the order in the dictionary, but that wouldn't really be solving the problem.

Edit: I have changed the code completely now using an ordered dictionary instead. But I'm not sure on how to check that they key is the same as the value that i have given.

from collections import OrderedDict
values = OrderedDict()
values[20] = 6
values[30] = 14
values[40] = 24
values[50] = 38
values[60] = 55
values[70] = 75

speed = int(input("Enter the test speed> "))
if speed in values.keys() :
  distance = int(input("Enter the stopping distance> "))
  if values.values[speed] = distance :
    None

values.values[speed] just brings up an error, and I'm pretty sure it's wrong. The program is for school, and I could just write it longer and it would work, but want to learn how dictionaries and other things work.

The program asks the user to enter a speed and a stopping distance, and if the stopping distance is short enough for the speed then it sends a message to the user saying so.

I thought that a dictionary where I can have a key as the speed and value as the distance would work, but I can't figure out a way to choose the distance linked to the speed that was entered or compare the distance in the dictionary to the distance entered.

You could try using an Ordered dictionary in python. This data structure essentially remembers the order of the values you put into your dictionary(different from the traditional dictionary).

Check this tutorial to get started: https://www.geeksforgeeks.org/ordereddict-in-python/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM