User orders a dictionary in python

0

I'm starting in python, and I need to make a program where the elements of a dictionary will be displayed randomly (randomly), and then the user will have to sort them. The dictionary is ready, but I can not think of how to do it so the user can order it.

dic = {1 : 'Primer paso', 2 : 'Segundo paso', 3 : 'Tercer paso'}
print dic_[1]
    
asked by Eduardo Herrera 12.07.2018 в 02:16
source

2 answers

0

I do not understand clearly what can mean that the user has to order a dictionary.

Pulling on my crystal ball, I see a possible interpretation of your question, which would be the following: "Given a list that has a certain natural order, it is presented to the disorderly user, and he must find out which one was the original order ".

Something like the following. The user is presented with the following on screen:

Pon los siguientes pasos en el orden correcto

1. Echar el huevo batido en la sartén
2. Batir la yema con la clara
3. Esperar que cuaje
4. Buscar un huevo
5. Romper el huevo
6. Degustar tortilla

The user reconstructs the correct sequence, and enters the sequence of numbers in the program: 4 5 2 1 3 6 . The program answers if the answer is correct or not.

Assuming that this is what you were asking, you do not see the need to use dictionaries since they are inherently disordered (in the sense that if you loop them in a loop for clave in diccionario: the order in which the keys do not come it is predictable). In your example you used integers as keys, which indicates that you are really thinking about a list.

One possible implementation (in Python 3) that would behave as described above would be the following:

import random

# Esta es la secuencia en el orden correcto que el usuario debe adivinar
pasos = [
    "Buscar un huevo",
    "Romper el huevo",
    "Batir la yema con la clara",
    "Echar el huevo batido en la sartén",
    "Esperar que cuaje",
    "Degustar tortilla"
]

# Sacamos una copia de esa secuencia
copia = list(pasos)

# y la desordenamos aleatoriamente
random.shuffle(copia)

# Ahora mostramos al usuario la secuencia desordenada
print("Pon los siguientes pasos en el orden correcto")
for i, txt in enumerate(copia):
  print("{}. {}".format(i+1, txt))

# Leemos (como cadena) el orden tecleado por el usuario
respuesta = input("Teclea el orden correcto (números separados por espacios): ")
# y convertimos esa cadena a una lista de números
numeros = [int(n) for n in respuesta.split()]

# Usamos esos números para crear una nueva lista, ordenada según la
# elección del usuario
ordenado = [copia[i-1] for i in numeros]

# Verificamos si esta lista es igual a la original
if ordenado == pasos:
  print("Correcto!")
else:
  print("Lo siento, ese no es el orden correcto")
    
answered by 12.07.2018 / 18:22
source
0

It seems to me that you are using python 2 because of the syntax of your print (I do not use it).

Already to begin with I suggest that if you are going to learn from scratch you learn python 3 which is newer, because python 2 will disappear its technical support by 2020 if I am not mistaken.

Going back to your question:

Python 2.x

import random
dic = {1 : 'Primer paso', 2 : 'Segundo paso', 3 : 'Tercer paso'}
print dic[random.choice(list(dic))]

Python 3.x

import random
dic = {1 : 'Primer paso', 2 : 'Segundo paso', 3 : 'Tercer paso'}
print (dic[random.choice(list(dic))])

Not much difference between python 2 and 3 but good.

  • import random : imports the random library.
  • random.choice(seq) : returns a random value of the sequence. As I understand it, this can not be a dictionario.
  • list([iterable]) : converts the sequence into a list. In case of using a dictionary, it will return a list of the keys (keys) in this one. It would be something similar to .keys() in a dictionary.

By combining all this what you do is:

  • Convert the dictionary to a list of keys.
  • Acquire a random key.
  • Use the key to obtain a dictionary value.
  • answered by 12.07.2018 в 04:40