Home > Back-end >  How to print out my items in my dictionary only once with my len() without it printing the number 9,
How to print out my items in my dictionary only once with my len() without it printing the number 9,

Time:12-17

How do I print out my items in my dictionary only once with my len() without it printing the number 9, 9 times. Please help me, I cant figure this out.

Heres my code:

d = {
  "Brand: ": "Honda",
  "model: ": "Pilot",
  "year: ": 2021
}
for x in d:
  print(len(d))

ls = ["Chevrolet", "Dodge", "Ford", "Honda", "Jeep", "Nissan", "Saturn", "Subaru", "Tesla", "Toyota"]
for x in ls:
  print(len(ls))

ri = raw_input("Enter 'd', if you want to see a dictionary for a car. Or enter 'ls', if you want to see a list of cars: ")

def cars(d, ls):
  print ri
  if ri == 'd':
    print d
  if ri == 'ls':
    print ls

cars(d, ls)

CodePudding user response:

for x in d: print(len(d))

You have a for loop running which is printing it multiple times, switch it to just print(len(d)) and that will fix it

CodePudding user response:

You're printing a len so that is what you see, change to the variable you iterate on

d = {"Brand: ": "Honda", "model: ": "Pilot", "year: ": 2021}
for key, val in d.items():
    print(key, val)

ls = ["Chevrolet", "Dodge", "Ford", "Honda", "Jeep", "Nissan", "Saturn", "Subaru", "Tesla", "Toyota"]
for x in ls:
    print(x)

CodePudding user response:

Your need is not clarified. Here is implementation for what i understood from your need.

d = {
  "Brand: ": "Honda",
  "model: ": "Pilot",
  "year: ": 2021
}

ls = ["Chevrolet", "Dodge", "Ford", "Honda", "Jeep", "Nissan", "Saturn", "Subaru", "Tesla", "Toyota"]

ri = raw_input("Enter 'd', if you want to see a dictionary for a car. Or enter 'ls', if you want to see a list of cars: ")

def cars(d, ls):
  print(ri)
  if ri == 'd':
    print(d)
  if ri == 'ls':
    print(len(ls))
    for l in ls:
        print(l)

cars(d, ls)

  • Related