简体   繁体   中英

How to print out my items in my dictionary only once with my len() without it printing the number 9, 9 times

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)

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

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)

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)

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