raspberrysupreme raspberrysupreme - 4 months ago 9
Python Question

How can I iterate dictionaries to get key and value in Python?

How can I iterate over a dictonary to get both the key and the value written out.

hey = {'a':67, 'b': 98}

>>>a-67
>>>b-98


No built in methods should be used. This is what I have tried so far.

for i in hey:
print(i)

>>>a
>>>b


This randomly iterates only over the keys.

for i in hey:
hey[i]

>>>67
>>>98


This gives me the values.

Can i combine these two perhaps? How would that look?

Answer

You can print two items with the same statement:

for i in hey:
    print(i, hey[i])

If you want the output as a-67, you can also use

for i in hey:
    print(i, "-", hey[i], sep="")