How do I print the key-value pairs of a dictionary in python

oaklander114 picture oaklander114 · Oct 30, 2014 · Viewed 709.2k times · Source

I want to output my key value pairs from a python dictionary as such:

key1 \t value1
key2 \t value2

I thought I could maybe do it like this:

for i in d:
    print d.keys(i), d.values(i)

but obviously that's not how it goes as the keys() and values() don't take an argument.

Answer

chepner picture chepner · Oct 30, 2014

Your existing code just needs a little tweak. i is the key, so you would just need to use it:

for i in d:
    print i, d[i]

You can also get an iterator that contains both keys and values. In Python 2, d.items() returns a list of (key, value) tuples, while d.iteritems() returns an iterator that provides the same:

for k, v in d.iteritems():
    print k, v

In Python 3, d.items() returns the iterator; to get a list, you need to pass the iterator to list() yourself.

for k, v in d.items():
    print(k, v)