¡Te damos la bienvenida a este reto!

1

Empezando con Python desde 0

Día 1

2

Variables, funciones y sintaxis básica

3

Tipos de datos: Numbers, Strings y Diccionarios

4

Playground - Retorna el tipo

Día 2

5

Operadores

6

Playground - Calcula la propina

Día 3

7

Condicionales

8

Playground - Averigua si un año es bisiesto

9

Ciclos

10

Playground - Dibuja un triangulo usando bucles

Día 4

11

Listas

12

Encuentra a los gatitos más famosos

13

Diccionarios

14

Obtén el promedio de los estudiantes

15

Tuplas

16

Obten la información de los paquetes

Día 5

17

Calcula la cantidad de letras en una oración

18

Encuentra el mayor palíndromo

Día 6

19

Sets

20

Encuentre la intersección de conjuntos

Día 7

21

List comprehension

22

Encuentra palabras con dos vocales

23

Dictionary Comprehension

24

Calcula la longitud de las palabras

Día 8

25

Funciones Lambda

26

Filtra mensajes de un user específico

27

Higher order functions

28

Crea tu propio método map

Día 9

29

Manejo de Errores y excepciones

30

Maneja correctamente los errores

31

Maneja las excepciones

Día 10

32

Playground - Crea un task manager usando closures

Día 11

33

Lectura de archivos de texto y CSV

Día 12

34

Programación orientada a objetos

35

Crea un auto usando clases

Día 13

36

Abstracción en Python

37

Playground - Crea un sistema de carrito de compras

38

Encapsulamiento en Python

39

Playground - Encapsula datos de los usuarios

Día 14

40

Herencia en Python

41

Playground - Jerarquía de animales usando herencia

Día 15

42

Polimorfismo en Python

43

Playground - Implementa un sistema de pagos

Día 16

44

Estructuras de datos en Python

45

Playground - Crea tu propia lista en python

46

Hash tables en Python

47

Playground - Implementación de una HashTable para Contactos

Día 17

48

Maps en Python

49

Playground - Crea un task manager con Maps

Día 18

50

Singly Linked List en Python

51

Playground - Implementación de una singly linked list

Día 19

52

Stacks en Python

53

Playground - Implementación de un stack

Día 20

54

Queues en Python

55

Playground - Implementación de una queue

Día 21

56

¡Lo lograste!

No tienes acceso a esta clase

¡Continúa aprendiendo! Únete y comienza a potenciar tu carrera

Obten la información de los paquetes

16/56

Aportes 76

Preguntas 1

Ordenar por:

¿Quieres ver más aportes, preguntas y respuestas de la comunidad?


.
.
.
.

.
.
.

.
.
.

.
.

.
.

.
.
.
.
.

.

def get_packages_info(packages):
   # Tu código aquí 👈
   weight = [package[1] for package in packages]
   tuple_destinations = tuple(package[2] for package in packages)
   destinations = {destino: tuple_destinations.count(destino) 
                    for destino in tuple_destinations}
   total_weight = round(sum(weight),2)
   return {"total_weight":  total_weight,
            "destinations": destinations
            }

🛡️🛡️Escudo anti-spoilers🛡️🛡️

Mi solución al reto:

def get_packages_info(packages):
  results = {
    "total_weight": 0.0,
    "destinations":{}
  }
  total_weight = 0.0
  for pack in packages:
    id, weight, dest = pack 
    if dest in results['destinations']:
      results['destinations'][dest] += 1
    else:
      results['destinations'][dest] = 1
    results['total_weight'] += weight
  results['total_weight']  = round(results['total_weight'],2)
  return results

def get_packages_info(packages):
    #"Crea un diccionario para almacenar la información de los paquetes"
    packages_info = {
        "total_weight": 0,     # "Inicializa el peso total en 0"
        "destinations": {}     # "Inicializa el diccionario de destinos vacío
    }
    
    # "Itera sobre cada paquete en la lista de paquetes"
    for package in packages:
        if package[2] in packages_info["destinations"]:
            # "Si el destino ya está en el diccionario de destinos, incrementa su contador en 1"
            packages_info["destinations"][package[2]] += 1
        else:
            # "Si el destino no está en el diccionario de destinos, crea una nueva entrada y establece su contador en 1"
            packages_info["destinations"][package[2]] = 1
        
        # "Suma el peso del paquete al peso total"
        packages_info["total_weight"] += package[1]
    

    # "Redondea el peso total a 2 decimales"
    packages_info["total_weight"] = round(packages_info["total_weight"], 2)
    
    # "Devuelve el diccionario con la información de los paquetes"
    return packages_info


get_packages_info([
    (1, 20, "Mexico"),
    (2, 15.5, "Colombia"),
    (3, 30, "Mexico"),
    (4, 12, "Argentina"),
    (5, 8.2, "Colombia"),
    (6, 25, "Mexico"),
    (7, 18.7, "Argentina"),
    (8, 5, "Colombia"),
    (9, 22.3, "Argentina"),
    (10, 14.8, "Colombia")
])


.
.
.
.
.
.
.
.
.
.

Mi solución:

def get_packages_info(packages):

  package_info = {}

  total_weight = 0
  for package in packages:
    total_weight += package[1]

  total_weight = round(total_weight, 2)

  destinations = {}
  for package in packages:
    destination = package[2]
    if destination not in destinations:
      destinations[destination] = 1
    else:
      destinations[destination] += 1

  package_info["total_weight"] = total_weight
  package_info["destinations"] = destinations

  return package_info

Escudo Anti spolers
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

def get_packages_info(packages):
   # Tu código aquí 👈
   total = 0
   destinos = {}
   for pack in packages:
      total += pack[1]
      if pack[2] in destinos:
         destinos[pack[2]] += 1
      else:
         destinos[pack[2]] = 1
   return {
      "total_weight": round(total, 2),
      "destinations": destinos
   }

Solución 😄…
.

.
.
.
.

def get_packages_info(packages):
   countries = [country for _, _, country in packages]
   
   destinations = {}

   destinations = {
      country: countries.count(country) 
      for country in countries
      if country not in destinations
      }

   total_weight = round(sum(
      package[1] 
      for package in packages
      ), 2)

   return {
      "total_weight": total_weight,
      "destinations": destinations
   }
Automatizando los destinos y que nos se repitan sin usar conjuntos. . . . . ```python def get_packages_info(packages): # Tu código aquí 👈 #Para el peso totalWeight = 0 for package in packages: weight = package[1] totalWeight += weight totalWeight = round(totalWeight, 2) #saliendo del bucle el peso total ya está en la variable "totalWeight" #para el diccionario de destinos destinationList = [] for destination in packages: country = destination[2] destinationList.append(country) #Contando para cada uno de los paises que no se repiten. #Se cuenta y luego se elimina tantas veces como se contó. unitaryCountry = [] countPackageCountry = [] for nCountry in destinationList: nUnitaryCountry = str(destinationList[0]) nCountPackageCountry = destinationList.count(nUnitaryCountry) unitaryCountry.append(destinationList[0]) countPackageCountry.append(nCountPackageCountry) for nRemove in range(nCountPackageCountry): destinationList.remove(nUnitaryCountry) #Los paises y su cantidad de paquetes los ponemos en un diccionario. diccionarioDestinos = {} n1 = 0 for nCountry1 in unitaryCountry: diccionarioDestinos[unitaryCountry[n1]] = countPackageCountry[n1] n1 += 1 #Ponemos el arreglo final en una variable. pesoTotalYDestinos = {"total_weight": totalWeight, "destinations": diccionarioDestinos} return pesoTotalYDestinos print(get_packages_info([ (1, 20, "Mexico"), (2, 15.5, "Colombia"), (3, 30, "Mexico"), (4, 12, "Argentina"), (5, 8.2, "Colombia"), (6, 25, "Mexico"), (7, 18.7, "Argentina"), (8, 5, "Colombia"), (9, 22.3, "Argentina"), (10, 14.8, "Colombia") ])) ```
Aquí dejo mi solución al ejercicio ![](https://static.platzi.com/media/user_upload/imagen-76d24fed-3b9c-42d0-868d-b0b0f65f9895.jpg)
¿Alguien me ayuda a entender por qué no logro aprobar el playground? ```python def get_packages_info(packages): # Tu código aquí 👈 result = {"total_weight" : 0, "destinations" : {} } for pack in packages: result["total_weight"] += pack[1] if pack[2] in result["destinations"]: result["destinations"][pack[2]] += 1 else: result["destinations"][pack[2]] = 1 result["total_weight"] = round(result["total_weight"], 2) return result ```def get\_packages\_info(packages):   # Tu código aquí 👈   result = {"total\_weight" : 0,    "destinations" : {}    }        for pack in packages:      result\["total\_weight"] += pack\[1]              if pack\[2] in result\["destinations"]:         result\["destinations"]\[pack\[2]] += 1      else:         result\["destinations"]\[pack\[2]] = 1               result\["total\_weight"] = round(result\["total\_weight"], 2)      return result
Aqui les dejo mi solución al reto: ```js def get_packages_info(packages): package_weights = [package[1] for package in packages] total_weight = round(sum(package_weights), 2) destination_frequencies = {} for package in packages: destination = package[2] destination_frequencies[destination] = destination_frequencies.get(destination, 0) + 1 return {"total_weight": total_weight, "destinations": destination_frequencies} packages = [ (1, 20, "Mexico"), (2, 15.5, "Colombia"), (3, 30, "Mexico"), (4, 12, "Argentina"), (5, 8.2, "Colombia"), (6, 25, "Mexico"), (7, 18.7, "Argentina"), (8, 5, "Colombia"), (9, 22.3, "Argentina"), (10, 14.8, "Colombia") ] package_info = get_packages_info(packages) print(package_info) ```
Hola, I just want to share the way I coded it ```js def get_packages_info(packages): result = { "total_weight": 0, "destinations": {} } countries = set([package[2] for package in packages]) result["destinations"] = {country: 0 for country in countries} for package in packages: result["destinations"][package[2]] += 1 result["total_weight"] = round(sum([package[1] for package in packages]), 2) return result ```def get\_packages\_info(packages): result = { "total\_weight": 0, "destinations": {} } countries = set(\[package\[2] for package in packages]) result\["destinations"] = {country: 0 for country in countries} for package in packages: result\["destinations"]\[package\[2]] += 1 result\["total\_weight"] = round(sum(\[package\[1] for package in packages]), 2) return result
Hola, I just want to share the way I coded it ```js def get_packages_info(packages): result = { "total_weight": 0, "destinations": {} } countries = set([package[2] for package in packages]) result["destinations"] = {country: 0 for country in countries} for package in packages: result["destinations"][package[2]] += 1 result["total_weight"] = round(sum([package[1] for package in packages]), 2) return result ```def get\_packages\_info(packages): result = { "total\_weight": 0, "destinations": {} } countries = set(\[package\[2] for package in packages]) result\["destinations"] = {country: 0 for country in countries} for package in packages: result\["destinations"]\[package\[2]] += 1 result\["total\_weight"] = round(sum(\[package\[1] for package in packages]), 2) return result

def get_packages_info(packages):

paises = list({z for (x,y,z) in packages})
paquetes = [y for (x,y,z) in packages]

total_peso = round(sum(paquetes),2)
total_paquetes = []

for pais in paises:
regpais = [pais]
tuplas_pais = [tup for tup in packages if (set(regpais) & set(tup))]
paquetes_pais = len([y for (x,y,z) in tuplas_pais])
total_paquetes.append(paquetes_pais)

resultado = {}
resultado[‘total_weight’] = total_peso
resultado[‘destinations’] = {
pais: total for pais, total in zip(paises, total_paquetes)
}

print(resultado)
return resultado

mi solución: ```js def get_packages_info(packages): dict_out={} dict_destinations={} total_weight: float=0 for info in packages: total_weight += info[1] if info[2] in dict_destinations: dict_destinations[info[2]] += 1 else: dict_destinations[info[2]]=1 dict_out["total_weight"]=round(total_weight,2) dict_out["destinations"]=dict_destinations return dict_out ```
Versión reducida para tener otra posible forma de solucionarlo. ```js def get_packages_info(packages): return { "total_weight": round(sum(package[1] for package in packages), 2), "destinations": {package[2]: sum(1 for p in packages if p[2] == package[2]) for package in packages} } ```
hi i did it!!!! ![](https://static.platzi.com/media/user_upload/image-00464d91-6098-4166-8556-530d886ac6bc.jpg)


.
.
.
.
.
.

def get_packages_info(packages):
  destination = {}
  peso = []
  for renglon in packages:
    peso.append(renglon[1])
    if renglon[2] in destination:
      for pais, num in destination.items():
        # print(pais,num)
        if pais == renglon[2]:
          # print("renglon",renglon[2])
          destination[pais] = (num + 1)
          # print (destination)

    else:
      destination[renglon[2]] = 1


  # print(l,sum(l))
  output = {}

  output["total_weight"]=  round(sum(peso),2)
  output["destinations"] = destination
  return output

hola comparto mi codigo, trate de no usar comprehension , porque la verdad asi lo entiendo mejor:
def get_packages_info(packages):
total_weight = 0.0
destinations = {}
destinations_list = []
total_packages = {}

for i in packages:
total_weight += i[1]
destinations_list.append(i[2])
for i in destinations_list:
destinations[i] = destinations_list.count(i)
total_packages[“total_weight”] = round (total_weight,2)
total_packages[“destinations”] = destinations
print(total_packages)

Input: get_packages_info (
[
(1, 20, “Mexico”),
(2, 15.5, “Colombia”),
(3, 30, “Mexico”),
(4, 12, “Argentina”),
(5, 8.2, “Colombia”),
(6, 25, “Mexico”),
(7, 18.7, “Argentina”),
(8, 5, “Colombia”),
(9, 22.3, “Argentina”),
(10, 14.8, “Colombia”)
]
)

package = [
  (1, 20, "Mexico"),
  (2, 15.5, "Colombia"),
  (3, 30, "Mexico"),
  (4, 12, "Argentina"),
  (5, 8.2, "Colombia"),
  (6, 25, "Mexico"),
  (7, 18.7, "Argentina"),
  (8, 5, "Colombia"),
  (9, 22.3, "Argentina"),
  (10, 14.8, "Colombia")
]

def get_packages_info(packages):
   # Tu código aquí 👈
    destinations = {}
    total_weigth = 0
    for package in packages:
        weight = package[1]
        total_weigth += weight
        llave = package[2]
        if llave in destinations:
            destinations[llave] += 1
        else: 
            destinations[llave] = 1
    final_dict = {"total_weight":round(total_weigth,2), "destinations":destinations} 
    return final_dict

if __name__ == "__main__":
   print(get_packages_info(package)) 
 
def get_packages_info(packages):
   weights_sum = 0
   destinations = {}
   
   for package in packages:
      weights_sum += package[1];
      if (not(package[2] in destinations)):
         destinations[package[2]] = 0
      
      if(package[2] in destinations): 
         destinations[package[2]] = destinations[package[2]] + 1
         

   return {
      "total_weight": round(weights_sum, 2),
      "destinations": destinations
   }

print(get_packages_info([
  (1, 20, "Mexico"),
  (2, 15.5, "Colombia"),
  (3, 30, "Mexico"),
  (4, 12, "Argentina"),
  (5, 8.2, "Colombia"),
  (6, 25, "Mexico"),
  (7, 18.7, "Argentina"),
  (8, 5, "Colombia"),
  (9, 22.3, "Argentina"),
  (10, 14.8, "Colombia")
]))
def get_packages_info(packages):
   # Tu código aquí 👈
  pass
  total_destinations = {}
  total_weight= 0

  for tuple in packages:
    total_weight += tuple[1]
  total_weight = round(total_weight,2)  
#print("peso_weight: ",peso_weight)
  destinations = {}  
  for tuple in packages:
    valores = tuple[2]
    if valores in destinations:
      destinations[valores] +=1
    else:
      destinations[valores] =1 
  
  total_destinations  ["total_weight"]   = total_weight
  total_destinations  ["destinations"] = destinations
  return total_destinations

def get_packages_info(packages):
    total_weight = 0
    destinos_dict = {}

    for pack in packages:
        total_weight += pack[1]
        destino = pack[2]
# Contamos los paquetes para cada destino usando un diccionario
        destinos_dict[destino] = destinos_dict.get(destino, 0) + 1
   
# Redondeamos el total_weight una vez al final
    total_weight = round(total_weight, 2)

# Creamos el diccionario final con los resultados
    new_dict = {"total_weight": total_weight, "destinations": destinos_dict}

    return new_dict
def get_packages_info(packages):
   names = { tupla[2] for tupla in packages}

   tuple3 = tuple()
   acum = 0
   for tupla in packages:
      acum+=tupla[1]
      tuple3 += tupla
   
   acum=round(acum,2)
   count = {name: tuple3.count(name) for name in names}

   return {"total_weight":acum , "destinations": count}

Esta es mi solución:

.
.
.
.
.
.
.
.
.
.

def get_packages_info(packages):
   total_weight = 0
   destinations = {}
   for package in packages:
      ide, weight, destination = package
      total_weight += weight

      if destination in destinations:
         destinations[destination] +=1
      else:
         destinations.update({destination: 1})
   return {
      "total_weight": round(total_weight,2),
      "destinations": destinations
   }

Humilde aporte

envios={
  "total_weight": 0,
    "destinations":{}
}

def get_packages_info(packages):
  
  for x in packages:
    
    envios["total_weight"]+= round(x[1],2)
    
    z=envios["destinations"].get(x[2]) 
    
    
    if z is None:
      
      envios["destinations"][x[2]]=1
    else:
      
      envios["destinations"][x[2]]+=1
    

  envios["total_weight"]=round(envios["total_weight"],2)
  print ( envios )
  

  
  pass


get_packages_info([
  (1, 20, "Mexico"),
  (2, 15.5, "Colombia"),
  (3, 30, "Mexico"),
  (4, 12, "Argentina"),
  (5, 8.2, "Colombia"),
  (6, 25, "Mexico"),
  (7, 18.7, "Argentina"),
  (8, 5, "Colombia"),
  (9, 22.3, "Argentina"),
  (10, 14.8, "Colombia")
])
...def get_packages_info(packages):
  # Tu código aquí 👈
  total_weight = 0
  destinations = []
  diccionario = {}
  veces = {}
  for i in packages:
    total_weight = total_weight + i[1]
    total_weight = round(total_weight, 2)
    destinations.append(i[2])

  for i in destinations:
    if i in veces :
      veces[i] += 1
    else:
      veces[i] = 1
  #print(veces)
  #print(type(veces))

  diccionario = {"total_weight":total_weight, "destinations":veces}
  #diccionario = {"total_weight":total_weight, "destinations": destinations}
  #print(type(destinations))
  #print(destinations)
  return diccionario
def get_packages_info(packages):
  """Function Get Packages Information"""
  
  total_weight = 0
  registration_pack = {
    "total_weight": 0,
    "destinations": {},
  }
  
  for pack in packages:
    total_weight += pack[1]

    if pack[2] not in registration_pack["destinations"]:
      registration_pack["destinations"][pack[2]] = 1
    else:
      registration_pack["destinations"][pack[2]] += 1

  total_weight = round(total_weight, 2)
  
  registration_pack["total_weight"] = total_weight
  
  return registration_pack



if __name__ == '__main__':
  # (id, weight, destination)
  packages = [
    (1, 20, "Mexico"),
    (2, 15.5, "Colombia"),
    (3, 30, "Mexico"),
    (4, 12, "Argentina"),
    (5, 8.2, "Colombia"),
    (6, 25, "Mexico"),
    (7, 18.7, "Argentina"),
    (8, 5, "Colombia"),
    (9, 22.3, "Argentina"),
    (10, 14.8, "Colombia")
  ]
  
  response = get_packages_info(packages)
  print(response)

Listo

Paquetes = [
(1, 20, “Mexico”),
(2, 15.5, “Colombia”),
(3, 30, “Mexico”),
(4, 12, “Argentina”),
(5, 8.2, “Colombia”),
(6, 25, “Mexico”),
(7, 18.7, “Argentina”),
(8, 5, “Colombia”),
(9, 22.3, “Argentina”),
(10, 14.8, “Colombia”)
]
def inventario(Paquetes):
Paquete = {}
Listo = {}
Destinos = {}
p = 0
PesoT = 0
MX = 0
AR = 0
CO = 0
for peso in Paquetes:
Paquete = Paquetes[p]
W = Paquete[1]
M = Paquete[2]
C = Paquete[2]
A = Paquete[2]
PesoT = PesoT + W
if M == “Mexico”:
MX += 1
if A == “Argentina”:
AR += 1
if C == “Colombia”:
CO += 1
p += 1
Listo = {“Peso tota”: PesoT, “Destinos”: {“Mexico”:MX,“Argentina”:AR,“Colombia”:CO}}
print(Listo)
inventario(Paquetes)

solución:

def get_packages_info(packages):
    total_weight =0
    ## creando el diccionario
    dictresultfinal={ 
        "total_weight": 0,
        "destinations": []
    }
    #lista de destinos
    listdestinations=[]
    listweights=[]
    #creando la tupla de destinos
    tupledestination=tuple(propais[2] for propais in packages)
 
    #creando la lista de weights
    listweights=[propweight[1] for propweight in packages]

    total_weight = round(sum(listweights),2)

    #agrupando y contando los paises
    listdestinations={propais: tupledestination.count(propais) for propais in tupledestination}

    # Agregando al diccionario
    dictresultfinal={'total_weight':total_weight, 'destinations': listdestinations}
    #print(dictresultfinal)
    return dictresultfinal

if __name__ == '__main__':
    response=get_packages_info([
        (1, 20, "Mexico"),
        (2, 15.5, "Colombia"),
        (3, 30, "Mexico"),
        (4, 12, "Argentina"),
        (5, 8.2, "Colombia"),
        (6, 25, "Mexico"),
        (7, 18.7, "Argentina"),
        (8, 5, "Colombia"),
        (9, 22.3, "Argentina"),
        (10, 14.8, "Colombia")
     ])
    print(response)

Solución:

def get_packages_info(packages):
   total_weight = sum(p[1] for p in packages)
   destinations = {}
   for p in packages:
      destinations[p[2]] = destinations.get(p[2], 0) + 1
   return {
      "total_weight": round(total_weight, 2),
      "destinations": destinations,
   }

El método get() nos devuelve el valor de la llave que le pasemos como primer parámetro, el segundo parámetro es opcional, que será el valor que devuelve el método en caso de no existir la llave.

def get_packages_info(packages):
    total_weight=0
    unique_countries=[]
    countries=[]
    
    for package in packages:
        total_weight+=package[1]
        countries.append(package[2])
        if package[2] not in unique_countries:
            unique_countries.append(package[2])

    total_weight=round(total_weight,2)
    destinations={country:countries.count(country) for country in unique_countries}
    
    return {
        'total_weight':total_weight,
        'destinations':destinations
        }

Mi solucion, me llevo tiempo pero se logro.

def get_packages_info(packages):
   # Tu código aquí 👈
    last_dict = dict()
    destinations = dict()
    total_weigth = 0

    for package in range(len(packages)):
        total_weigth += packages[package][1]

    n = 1
    for package in range(len(packages)):
        if packages[package][2] not in destinations:
            destinations[packages[package][2]] = n
        else:
            destinations[packages[package][2]] += n

    last_dict['total_weight'] = round(total_weigth,2)
    last_dict['destinations'] = destinations

    return last_dict
    #print(destinations)
    
packages = [
  (1, 20, "Mexico"),
  (2, 15.5, "Colombia"),
  (3, 30, "Mexico"),
  (4, 12, "Argentina"),
  (5, 8.2, "Colombia"),
  (6, 25, "Mexico"),
  (7, 18.7, "Argentina"),
  (8, 5, "Colombia"),
  (9, 22.3, "Argentina"),
  (10, 14.8, "Colombia")
]


result = get_packages_info(packages)
print(result)```
def get_packages_info(packages):
   
   weight = 0
   city = []
   unique_city = []
   destinations = {}
   
   for i in packages:
      weight += i[1]

      city.append(i[2])

      for j in city:
         if j not in unique_city:
            unique_city.append(j) 

   for k in unique_city:
      destinations_city = city.count(k)

      destinations[k] = destinations_city 
        

   packages_info = {
      "total_weight": round(weight,2),
      "destinations": destinations
   }   

   return packages_info

Este me salió en el primer intento, me siento orgulloso:
Nota: si no te pasa lo mismo no te preocupes, no a menudo pasa.


.
.

def get_packages_info(packages):
  destinations = {}
  totalWeight = 0

  for package in packages:
    totalWeight += package[1]
    if package[2] in destinations: 
        destinations[package[2]]+= 1
        continue

    destinations[package[2]] = 1

  return {"total_weight": round(totalWeight,2), "destinations": destinations}

Dios perdóname por tanta variable pero a mi destino llegué.
Sin más preámbulo:

def get_packages_info(packages):
  suma_pesos = 0      #peso total de los paquetes
  lista_paises = []   #lista de los paises si repetición
  gran_tupla = ()     #conjunto de todas las tuplas
  resumen_paises = {} #nro de envios por pais
  
  #lista de paies
  for envio in packages:
    #crea gran tupla
    gran_tupla +=envio
    #suma de todos los pesos de paquetes
    suma_pesos+=envio[1]

    if envio[2] not in lista_paises:
      #crea una lista de los paises sin repetición
      lista_paises.append(envio[2])
  
  for pais in lista_paises:
    #obtiene la cantidad de envios por país
    resumen_paises[pais] = gran_tupla.count(pais)
  
  #retorna el diccionario solicitado
  return {"total_weight":round(suma_pesos,2),"destinations":resumen_paises}


.
.
.
.
.
.
.
.

# Obten la información de los paquetes

def get_packages_info(packages):
  rta = {
    "total_weight": 0, # aquí el peso total se irá incrementanto de la suma de cada paquete como lo indica la linea 114
    "destinations": {} # aquí creamos un conjunto de paises para que no haya duplicados que se obtendran de la variable local existDestination
  }
  
  for package in packages:
    weight = package[1] # aqui para que entiendan tenemos una lista de tuplas por ejemplo (1, 20, "Mexico"), donde se leen (0, 1, 2) entoces en la linea 14 sumara todos los pesos de los paquetes
    destination = package[2] # aqui te nemos la posicion 2 de la tupla donde vamos a almacenarlos en la variable destination
    existDestination = rta["destinations"].get(destination)
    
    rta["total_weight"] += weight # esto es la suma de todos los pesos
    
    if existDestination is None: # aqui como exist_Destination empieza vacia (None) se get(obtine) de package[2] (ojo yo confudia que era leer la segunda tupla y es incorrecto) que es la primera tupla en la tercera posicion (1, 20, "Mexico")
      rta["destinations"][destination] = 1
    else:
      rta["destinations"][destination] += 1 # despues como ya no estara vacia (None) se le incremente un 1 para que sea 2 y obtenemos el siguiente pais, total si se repite no se puede duplicar porque los estamos almacenando en un conjunto (set)

  rta["total_weight"] = round(rta["total_weight"], 2) # es para que con round solo nos de los ultimos 2 digitos decimales

  return rta # retornamos a la variable rta

response = get_packages_info([
  (1, 20, "Mexico"),
  (2, 15.5, "Colombia"),
  (3, 30, "Mexico"),
  (4, 12, "Argentina"),
  (5, 8.2, "Colombia"),
  (6, 25, "Mexico"),
  (7, 18.7, "Argentina"),
  (8, 5, "Colombia"),
  (9, 22.3, "Argentina"),
  (10, 14.8, "Colombia")
])

print(response) # imprimimos la funcion get_packages_info

# {'total_weight': 171.5, 'destinations': {'Mexico': 3, 'Colombia': 4, 'Argentina': 3}}

SOLUTION
.
.
.
.
.
.
.
.
.
.
.
.

from functools import reduce

def get_packages_info(packages):
    weights = [package[1] for package in packages]
    weights.append(0)
    countries = [package[2] for package in packages]

    country_output = {country: countries.count(country)
                        for country in countries }
    
    total_weight = 0 if len(weights) < 0 else reduce(lambda x, y: x + y , weights)

    return {
        "total_weight": round(total_weight, 2),
        "destinations": country_output
    }

Mi respuesta
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.

def get_packages_info(packages):
    total_weight = round(sum([pack[1] for pack in packages]), 2)
    total_deliveries = tuple([country [2] for country in packages])
    dict_packages = {country: total_deliveries.count(country) for country in total_deliveries}
    return { 'total_weight': total_weight, 'destinations': dict_packages}

Algo nuevo que aprendí haciendo este ejercicio es que cuando usas una tupla con valores repetidos como clave en un diccionario que quieres crear, automáticamente elimina los duplicados, tal cual como se aprecia en el diccionario ‘dict_packages’.

Mi solución:
.
.
.
.
.
.
.
.
.

def get_packages_info(packages):
   total_weight= round(sum([pack[1] for pack in packages]),2)
   countries = list(set([pack[2] for pack in packages]))
   all_countries= [pack[2] for pack in packages]
   countar= [all_countries.count(destino) for destino in countries]
   destinations = dict(zip(countries, countar))
   return {
      "total_weight": total_weight,
      "destinations": destinations
   }

Comparto mi código!
.

.
.
.
.
.

def get_packages_info(packages):
   resume = {
      "total_weight": 0,
      "destinations": {}
   }
   for package in packages:
      resume["total_weight"] += package[1]
      if package[2] in resume["destinations"]:
         resume["destinations"][package[2]] += 1
      else:
         resume["destinations"][package[2]] = 1
   resume["total_weight"] = round(resume["total_weight"], 2)
   return resume

.
.
.
.
:
:
:
.
.
.
:
:
:

def get_packages_info(packages):
  # Tu código aquí
  total_weight = 0
  #paquetes por destino
  destinations = { pais: 0 for pais in set([envio[2] for envio in packages])}

  for envio in packages:
    total_weight += envio[1]
    destinations[envio[2]] += 1
  return { 'total_weight': round(total_weight, 2), 'destinations':destinations } 

Mi aporte:
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

def get_packages_info(packages):
   # Tu código aquí 👈
  totalWeight = 0
  destAndPack = {}
  for info in packages:
    totalWeight += info[1]
    if info[2] in destAndPack:
      destAndPack[info[2]] += 1
    else:
      destAndPack[info[2]] = 1
  return {
    'total_weight': round(totalWeight, 2),
    'destinations': destAndPack
  }


.
.
.


.

.
Les comparto mi solución


Creo que cada uno vino con una solución diferente, esta es mi solución, no he visto a nadie que haya hecho como yo lo hice, espero les ayude.

def get_packages_info(packages):
   packages_info = {
   "total_weight": 0,
   "destinations": {
      }
   }
   total_weight = 0
   destinations = []

   for i in packages:
      total_weight += i[1]
      destinations.append(i[2])

   destinations_no_duplicates = set(destinations)
   for i in destinations_no_duplicates:
      packages_info["destinations"][i] = destinations.count(i)

   packages_info["total_weight"]= round(total_weight,2)
   return packages_info

=

=

=

=

=

=

=

=

=

=

def get_packages_info(packages):
  destinations={}
  total_weight=0
  for package in packages:
    country=package[2]
    total_weight+=package[1]
    if country in destinations:
      destinations[country] = destinations[country] + 1
    else:
      destinations[country] = 1
  output={
      "total_weight": round(total_weight,2),
      "destinations": destinations
  }
  return output

entrada=[ (1, 20, "Mexico"), (2, 15.5, "Colombia"), (3, 30, "Mexico"), (4, 12, "Argentina"), (5, 8.2, "Colombia"), (6, 25, "Mexico"), (7, 18.7, "Argentina"), (8, 5, "Colombia"), (9, 22.3, "Argentina"), (10, 14.8, "Colombia") ]
print(get_packages_info(entrada))

def get_packages_info(packages):
    
        total_weight = 0
        destinations = {}
    
        for package in packages:
            total_weight += package[1]
            destinations[package[2]] = destinations.get(package[2], 0) + 1
    
        return {
            "total_weight": round(total_weight, 2),
            "destinations": destinations
        }
        pass

Mi solución:
.
.
.
.
.
.
.

def get_packages_info(packages):
   unique_countries = []
   destinations = {}
   total_weight = 0

   for (id, weight, destination) in packages:
      total_weight += weight
      if destination not in unique_countries:
         unique_countries.append(destination)
         destinations[destination] = 1
      else:
         destinations[destination] += 1
   
   total_weight = round(total_weight, 2)
   
   return {
      "total_weight": total_weight,
      "destinations": destinations
   }
def get_packages_info(packages):
  # diccionario output
  rta = {
    "total_weight" : 0,
    "destinations" : {}
  }
  # (id, weight, destination)
  # "total_weight": El peso total de los paquetes.
  # "destinations": Un diccionario con los destinos como claves y la cantidad de paquetes como valores.
  total_weight = 0
  
  for package in packages:
    # desempaqueto las tuplas
    id , weight, destination = package
    # sumamos el peso del paquete al peso total 
    rta["total_weight"] += weight
    rta["total_weight"] = round(rta["total_weight"], 2)

    # incrementamos el contador para el destino del paquete
    if destination in rta["destinations"]:
      rta["destinations"][destination] +=1
    else:
      rta["destinations"][destination] =1

  return rta
      
response = get_packages_info([
  (1, 20, "Mexico"),
  (2, 15.5, "Colombia"),
  (3, 30, "Mexico"),
  (4, 12, "Argentina"),
  (5, 8.2, "Colombia"),
  (6, 25, "Mexico"),
  (7, 18.7, "Argentina"),
  (8, 5, "Colombia"),
  (9, 22.3, "Argentina"),
  (10, 14.8, "Colombia")
])

print(response)


.
.
.
.
.
.

def get_packages_info(packages):
  total = {
    'total_weight': 0,
    'destinations': {}
  }

  for package in packages:
    peso = package[1]
    pais = package[2]
    total['total_weight'] += round(peso, 2)

    if pais in total['destinations']:
          total['destinations'][pais] += 1
    else:
          total['destinations'][pais] = 1

    total['total_weight'] = round(total['total_weight'], 2)
    
  return total

packages = [
  (1, 20, "Mexico"),
  (2, 15.5, "Colombia"),
  (3, 30, "Mexico"),
  (4, 12, "Argentina"),
  (5, 8.2, "Colombia"),
  (6, 25, "Mexico"),
  (7, 18.7, "Argentina"),
  (8, 5, "Colombia"),
  (9, 22.3, "Argentina"),
  (10, 14.8, "Colombia")
]

response = get_packages_info(packages)
print(response)

Aquí mi solución sin duda necesito seguir practicando mucho para saber como se manipulan las listas y la tuplas


.
.
.
¡Cuarto día listo! 🐍👌🏼
.
.
.
.

def get_packages_info(packages):
  #creo una lista con los pesos
  pesos = [i[1] for i in packages]

  #creo una tupla con los destinos
  destinos = tuple(i[2] for i in packages)

  #creo el diccionario destinos:frecuencia
  dictDestinos = {i: destinos.count(i) for i in destinos}

  #cálculo del peso total
  pesoTotal = round(sum(pesos),2)
  
  return {"total_weight":  pesoTotal, "destinations": dictDestinos}

Mi aporte

.
.
.
.
.
.

def get_packages_info(packages):
    
    peso_total = 0
    destinos = {}
    for tupla in packages:
        destino = tupla[2]
        peso_total +=  tupla[1]
        
        if destino not in destinos:
            destinos[destino] = 0
        
        destinos[destino] += 1
    
       
    resultado = {'total_weight': round(peso_total,2),
                 'destinations': destinos
                 }
    return resultado
    pass


resultado = get_packages_info([
  (1, 20, "Mexico"),
  (2, 15.5, "Colombia"),
  (3, 30, "Mexico"),
  (4, 12, "Argentina"),
  (5, 8.2, "Colombia"),
  (6, 25, "Mexico"),
  (7, 18.7, "Argentina"),
  (8, 5, "Colombia"),
  (9, 22.3, "Argentina"),
  (10, 14.8, "Colombia")
])

print(resultado)

la “indentation” me vuelve loco!


.
.
.
.
.
.
.
.
.

def get_packages_info(packages):
   result = {
      'total_weight': 0,
      'destinations': {}
   }
   for package in packages:
      result['total_weight'] += package[1]
      if package[2] not in result['destinations']:
         result['destinations'][package[2]] = 0
      result['destinations'][package[2]] += 1

   result['total_weight'] = format(result['total_weight'], ".2f")

   return result
def get_packages_info(packages):
  total_weight = 0
  destinations = {}

  for package in packages:
    weight = package[1]
    destination = package[2]

    total_weight += weight

    if destination not in destinations:
      destinations[destination] = 0

    destinations[destination] += 1

  return {
   "total_weight": float(round(total_weight, 2)),
    "destinations": destinations
  }

def get_packages_info(packages):
    destino=[]
    lista=[]
    sum=0
    paquete=[]
    for i in packages:
        if i[2] not in destino:
            destino.append(i[2])
        sum=sum+i[1]
        lista.append(i[2])
    lista=tuple(lista)
    for i in destino:
        x=lista.count(i)
        paquete.append(x)
    diccionario_1={destinos:paquetes for (destinos,paquetes) in zip(destino,paquete)}
    diccionario={"total_weight":round(sum,2),"destinations":diccionario_1}    
    return diccionario



La primera solucion retorna lo solicitado excepto que no hace la suma de las coincidencias de los paises, en cada uno siempre me daba 0. (quizas algun experto pueda indicarme que es lo que esta mal)
La segunda funcion si corre bien!

def get_packages_info(packs):
   total = round(sum(tup[1] for tup in packs), 2)
   dest = {c: packs.count(c) for _, _, c in packs}
   return {
      'total_weight': total,
      'destinations': dest,
   }

def get_packages_info(packs):
   total = round(sum(tup[1] for tup in packs), 2)
   countries = [tup[2] for tup in packs]
   dest = {c: countries.count(c) for c in countries}
   return {
      'total_weight': total,
      'destinations': dest,
   }

Mi solución

def get_packages_info(packages):

   destinations = tuple((pack[2] for pack in packages))
   places = {d:destinations.count(d) for d in set(destinations)}
   weight = sum(tuple(pack[1] for pack in packages))
   
   return {
      "destinations": places,
      "total_weight": round(weight, 2)
   }

print(get_packages_info([
  (1, 20, "Mexico"),
  (2, 15.5, "Colombia"),
  (3, 30, "Mexico"),
  (4, 12, "Argentina"),
  (5, 8.2, "Colombia"),
  (6, 25, "Mexico"),
  (7, 18.7, "Argentina"),
  (8, 5, "Colombia"),
  (9, 22.3, "Argentina"),
  (10, 14.8, "Colombia")
]))      

Mi forma

def get_packages_info(packages):
  result = {
    "total_weight":0,
    "destinations":{}
  }
  total_weight = 0
  countriesRepeat = {}
  
  for package in packages:
    total_weight += package[1]
    country = package[2]
    if country in countriesRepeat:
      countriesRepeat[country]+=1
    else:
      countriesRepeat[country]=1
      
  result['total_weight']=round(total_weight,2)
  result['destinations']=countriesRepeat
  return result

Mi solucion amigos
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

def get_packages_info(packages):
  countries = [i[2] for i in packages]
  return {
    "total_weight": round(sum(i[1] for i in packages), 2),
    "destinations":
    {country: countries.count(country)
     for country in countries}
  }

Me estaba dando error por que mi variable no se llamaba exactamente igual “destionations”, entonce por el playground si usar las variables que coloquen.

aqui mi aporte
**
**
**
**
**
**
**
**
**
**
**
**
**

def get_packages_info(packages):
   # Tu código aquí 👈
   i = 0
   total_weight = 0
   destinations ={}
   for package in packages:
      if package[2] in destinations:
         numero = destinations[package[2]] 
         numero +=1
         destinations[package[2]]=numero
      else:
         destinations[package[2]] = 1  
      total_weight += package[1]
   return {"total_weight": round(total_weight,2), "destinations": destinations}

Después del anterior a este le tomé la mano rápido

.
.
.
.
.
.
.
.

def get_packages_info(packages):
   # Tu código aquí 👈
   total_peso = round(sum(item[1] for item in packages),2)
   destinos = {package[2]: sum(1 for p in packages if p[2] == package[2]) for package in packages}
   return {"total_weight":total_peso, "destinations": destinos}

Aqui mi solucion
.
.
.
.
.
.
.

from collections import Counter

def get_packages_info(packages):
   # Tu código aquí 👈
   total_weight = 0
   countries = []
   for i in packages:
      total_weight += i[1]
      countries.append(i[2])
   destinations = Counter(countries)
   destinations = dict(destinations)
    
   return {'total_weight': round(total_weight, 2), 'destinations': destinations}
def get_packages_info(packages):
   total_weight=0
   destinations={}
   for i in packages:
      id,peso,pais = i
      total_weight=total_weight+peso
      if pais not in destinations.keys():
         destinations[pais]=1
      else:
         destinations[pais]=destinations[pais]+1

   return({"total_weight":round(total_weight,2),"destinations":destinations})
def get_packages_info(packages):
   # Tu código aquí 👈
  total_weight = 0
  destination = {}
  for pack in packages:
    weight = pack[1]
    country = pack[2]
    total_weight += weight
    if country in destination:
      destination[country] += 1
    else:
      destination[country] = 1
  total_weight = round(total_weight,2)
  #total_weight = "{:.2f}".format(total_weight)
  output = {
    "total_weight": total_weight,
    "destinations": destination
  }
  return output
  pass
imput = [
  (1, 20, "Mexico"),
  (2, 15.5, "Colombia"),
  (3, 30, "Mexico"),
  (4, 12, "Argentina"),
  (5, 8.2, "Colombia"),
  (6, 25, "Mexico"),
  (7, 18.7, "Argentina"),
  (8, 5, "Colombia"),
  (9, 22.3, "Argentina"),
  (10, 14.8, "Colombia")
]
print(get_packages_info(imput))


o
o
o
o
o
o
o

def get_packages_info(packages):
   diccionario = {}
   destinos = {}
   peso_total = 0

   for paquete in packages:
      peso_total += paquete[1]
      if paquete[2] in destinos:
         destinos[paquete[2]] += 1
      else: 
         destinos[paquete[2]] = 1 

   peso_total = round(peso_total,2)    
   diccionario["total_weight"] = peso_total  
   diccionario["destinations"] = destinos    

   return diccionario


print(get_packages_info([
  (1, 20, "Mexico"),
  (2, 15.5, "Colombia"),
  (3, 30, "Mexico"),
  (4, 12, "Argentina"),
  (5, 8.2, "Colombia"),
  (6, 25, "Mexico"),
  (7, 18.7, "Argentina"),
  (8, 5, "Colombia"),
  (9, 22.3, "Argentina"),
  (10, 14.8, "Colombia")
]
))    



.
.
.
.
.
.
.
.
.
.
.
.
.

def get_packages_info(packages):
   # Variables para devolver el resultado y calcular el peso total
   result = {}
   total_weight = 0
   destinations = {}
   # Bucle para manejar los pesos y llenar el diccionario de destinos
   for pack in packages:
      total_weight += pack[1]
      if pack[2] in destinations:
         destinations[pack[2]] += 1
      else:
         destinations[pack[2]] = 1


def get_packages_info(packages):
   result = {
      "total_weight": 0,
      "destinations": {}
   }
   for package in packages:
      result['total_weight'] += package[1]
      if not package[2] in result['destinations']:
         result['destinations'][package[2]] = 1
      else:
         result['destinations'][package[2]] += 1
   result['total_weight'] = round(result['total_weight'],2)
   return result
   pass


.
.
.
.
.

def get_packages_info(packages):
   # Tu código aquí 👈
   packages_info = { 
       'total_weight' : 0,
       'destinations' : {
       }
   }
   total_weight = 0
   for package in packages:
       total_weight += package[1]
       country_key = package[2]
       if  country_key in packages_info['destinations']:
           packages_info['destinations'][country_key] += 1
       else:
           packages_info['destinations'][country_key] = 1
       
   packages_info['total_weight'] = round(total_weight,2)
   return packages_info


.
.
.

def get_packages_info(packages):
    total_weight = 0.0
    destinations = {}
    for package in packages:
        total_weight += package[1]
        destination = package[2]
        destinations[destination] = destinations.get(destination, 0) + 1
    return {
        "total_weight": round(total_weight,2),
        "destinations": destinations
    }


*
*
*
*
*

def get_packages_info(packages):
    total_weight = 0
    destinations = {}
    for package in packages:
        total_weight += package[1]
        if package[2] not in destinations:
            destinations[package[2]] = 1
        else:
            destinations[package[2]] += 1
    total_weight = round(total_weight, 2)
    packages_info = {"total_weight": total_weight, "destinations": destinations}
    return packages_info
```python def get_packages_info(packages): package_weights = [package[1] for package in packages] total_weight = round(sum(package_weights), 2) destination_frequencies = {} for package in packages: destination = package[2] destination_frequencies[destination] = destination_frequencies.get(destination, 0) + 1 return {"total_weight": total_weight, "destinations": destination_frequencies} packages = [ (1, 20, "Mexico"), (2, 15.5, "Colombia"), (3, 30, "Mexico"), (4, 12, "Argentina"), (5, 8.2, "Colombia"), (6, 25, "Mexico"), (7, 18.7, "Argentina"), (8, 5, "Colombia"), (9, 22.3, "Argentina"), (10, 14.8, "Colombia") ] package_info = get_packages_info(packages) print(package_info) ```
undefined