Solved

Looping over a dict gives only keys?

SamPriceOP

for x in planets: gives me only the names. How do I get the values too?

2

Comments 5

Join the discussion

Already have an account? Log in

  1. EmmaCodes Solutionreplies: 1

    Use .items():

    for name, distance in planets.items():
        print(f"{name}: {distance} AU")

    .values() gives only values, .keys() only keys (same as looping over the dict directly).

    8
    1. MateoGreplies: 1

      Dicts keep insertion order since Python 3.7, so you'll see items in the order you added them.

      1
      1. FreyaL

        lambda looks scary at first but this pattern is used everywhere. Worth learning.

        5
      2. CharlieH

        To loop sorted by value: for name, d in sorted(planets.items(), key=lambda kv: kv[1]):

        4