0

Simple question regarding nested loops.

stocks = {'GE': 6.28, 'XOM': 39.8}
for quote in stocks.values():
    print(quote)

    for symbol in stocks.keys():
        print(symbol)

        print('You have purchased', symbol, 'for', quote)

Output:

GE
You have purchased GE for 39.8
XOM
You have purchased XOM for 39.8

Why does it state that GE was purchased at 39.8 and not 6.28? I tried to indent and dedent the loop code but to no luck. Please help?

3 Answers3

1

If you're trying to print the key and value of a dict, then just unpack both in one for loop:

for symbol, quote in stocks.items():
    print(symbol)
    print('You have purchased', symbol, 'for', quote)
S.Chauhan
  • 156
  • 2
  • 8
1

Dictionaries are not (typically) ordered.

You will need to print in the same order as you traverse:

for k, v in stocks.items():
    print(k)
    print('You have purchased', k, 'for', v)
JacobIRR
  • 8,545
  • 8
  • 39
  • 68
1

This is the recommended iteration for dictionaries in python.

stocks = {'GE': 6.28, 'XOM': 39.8}
for key,value in stocks.items():
  print('You have purchased', key, 'for', value)