I need to create a dictionary. I have its values in a list but I don't have its keys. Its keys are just numbers (1,2,3,4 ...). "Lista" is a list that has the values. The code is the next:
nombres= ["Martin", "Milu","Anastasia", "Lupita", "Tomasa", "Pelusa", "Genoveva","Motita"]
tipos= ["canino", "canino", "felino", "felino", "felino", "canino", "bovino", "roedor"]
edades= [12, 9, 10, 8, 9, 2, 14, 1]
pesos= [33, 26, 4, 5, 5, 6, 106.4, 0.34]
numeros=["1","2","3","4","5","6","7","8"]
lista = []
lista.append(nombres)
lista.append(tipos)
lista.append(edades)
lista.append(pesos)
newlist=lista
diccionario = {}
## Dictionary
lista = [[lista[col][row] for col in range(4)] for row in range(8)]
The dictionary looks like: {“1” : [Martín, “canino”, 12, 33] , “2” : [“Milú”, “canino”, 9, 26] , “3” : [“Anastasia” ,“felino” , 10, 4] , “4” : [“Lupita” , “felino” , 8 , 5] ... }
CodePudding user response:
You can use enumerate
to get the numbers along with your list. Also you can use zip
to simplify your code that makes lista
:
nombres= ["Martin", "Milu","Anastasia", "Lupita", "Tomasa", "Pelusa", "Genoveva","Motita"]
tipos= ["canino", "canino", "felino", "felino", "felino", "canino", "bovino", "roedor"]
edades= [12, 9, 10, 8, 9, 2, 14, 1]
pesos= [33, 26, 4, 5, 5, 6, 106.4, 0.34]
output = dict(enumerate(zip(nombres, tipos, edades, pesos), start=1))
print(output)
# {1: ('Martin', 'canino', 12, 33), 2: ('Milu', 'canino', 9, 26),
# 3: ('Anastasia', 'felino', 10, 4), 4: ('Lupita', 'felino', 8, 5),
# 5: ('Tomasa', 'felino', 9, 5), 6: ('Pelusa', 'canino', 2, 6),
# 7: ('Genoveva', 'bovino', 14, 106.4), 8: ('Motita', 'roedor', 1, 0.34)}
If you do want to use numeros
as your keys, you can instead use nested zip
:
output = dict(zip(numeros, zip(nombres, tipos, edades, pesos)))
# {'1': ('Martin', 'canino', 12, 33), ...}
However, usually people might prefer a data structure like the following:
keys = ["nombre", "tipo", "edad", "peso"]
output = [dict(zip(keys, info)) for info in zip(nombres, tipos, edades, pesos)]
print(output) # [{'nombre': 'Martin', 'tipo': 'canino', 'edad': 12, 'peso': 33}, ...]
print(output[0]['edad']) # 12
Or alternatively, assuming the names are unique:
output = {nombre: {'tipo': tipo, 'edad': edad, 'peso': peso}
for nombre, tipo, edad, peso in zip(nombres, tipos, edades, pesos)}
print(output) # {'Martin': {'tipo': 'canino', 'edad': 12, 'peso': 33}, ...}
print(output['Tomasa']['peso']) # 5
CodePudding user response:
Perhaps the function "enumerate" will help you. Something like this:
nombres= ["Martin", "Milu","Anastasia", "Lupita", "Tomasa", "Pelusa", "Genoveva","Motita"]
result = {key: value for key, value in enumerate(nombres, start=1)}