raspberrysupreme raspberrysupreme - 1 year ago 69
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}


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

for i in hey:


This randomly iterates only over the keys.

for i in hey:


This gives me the values.

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

Answer Source

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="")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download