279

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.

codeforester
  • 39,467
  • 16
  • 112
  • 140
oaklander114
  • 3,143
  • 3
  • 16
  • 24
  • possible duplicate of [Python: how to print a dictionary's key?](http://stackoverflow.com/questions/5904969/python-how-to-print-a-dictionarys-key) – Mauro Baraldi Oct 30 '14 at 18:32

12 Answers12

521

Python 2 and Python 3

i is the key, so you would just need to use it:

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

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)

Python 2

You can get an iterator that contains both keys and values. 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
Gulzar
  • 23,452
  • 27
  • 113
  • 201
chepner
  • 497,756
  • 71
  • 530
  • 681
97

A little intro to dictionary

d={'a':'apple','b':'ball'}
d.keys()  # displays all keys in list
['a','b']
d.values() # displays your values in list
['apple','ball']
d.items() # displays your pair tuple of key and value
[('a','apple'),('b','ball')

Print keys,values method one

for x in d.keys():
    print(x +" => " + d[x])

Another method

for key,value in d.items():
    print(key + " => " + value)

You can get keys using iter

>>> list(iter(d))
['a', 'b']

You can get value of key of dictionary using get(key, [value]):

d.get('a')
'apple'

If key is not present in dictionary,when default value given, will return value.

d.get('c', 'Cat')
'Cat'
Alex E
  • 3
  • 3
Hackaholic
  • 19,069
  • 5
  • 54
  • 72
37

Or, for Python 3:

for k,v in dict.items():
    print(k, v)
Patrick Beeson
  • 1,667
  • 21
  • 36
31

The dictionary:

d={'key1':'value1','key2':'value2','key3':'value3'}

Another one line solution:

print(*d.items(), sep='\n')

Output:

('key1', 'value1')
('key2', 'value2')
('key3', 'value3')

(but, since no one has suggested something like this before, I suspect it is not good practice)

Nara Begnini
  • 473
  • 4
  • 6
  • 6
    i think this should definitely be a more accepted answer! ... i feel this answer demos the type of power in python that is mostly ignored... you can also do the follow to get rid of the '()' ... `print(*[f"{': '.join(map(str,v))}" for i,v in enumerate(list(d.items()))], sep='\n')` .... or you can do the following to conveniently print index #'s as well `print(*[f"[{i}] {': '.join(map(str,v))}" for i,v in enumerate(list(d.items()))], sep='\n')` – greenhouse Jul 16 '19 at 11:03
  • Can somebody explain why the * is needed and how it converts dict_values to actual values. Thank you. – MichaelE Jan 20 '21 at 22:28
  • 4
    The * operator also works as an "unpacker" (besides multiplying). So what happens is that it unpacks the dictionary items. It doesn't convert, I would say it "opens" the box that d.items() is, and print receives the contents. "unpacking operator python" is the keyword for a more technical explanation. – Nara Begnini Jan 22 '21 at 01:04
  • not sure why you think this might be not a good practice, while i think a request to access to I/O with `print` command per each key-pair is much worse practice from efficiency point of view – Leon Proskurov Apr 18 '23 at 11:42
6
for key, value in d.iteritems():
    print key, '\t', value

For Python 3.x

for key, value in d.items():
    print(f'{key}\t{value}') 
Mauro Baraldi
  • 6,346
  • 2
  • 32
  • 43
  • I actually tried to use d.iteritems(): first and got AttributeError: 'dict' object has no attribute 'iteritems'. I was using Python 3 and switched ti d.items() and it worked, because iteritems seems to have been removed from Python 3. You can read about the difference between Python 2 and 3 in this thread: https://stackoverflow.com/questions/30418481/error-dict-object-has-no-attribute-iteritems – AwfulPersimmon Apr 04 '23 at 19:29
6

You can access your keys and/or values by calling items() on your dictionary.

for key, value in d.iteritems():
    print(key, value)
goulon
  • 69
  • 1
  • 3
  • 2
    you said ```items()``` in the first line of your text and in the code you put ```iteritems()```. In python3x the correct way is the ```dict.items()``` as you said first. – Joel Carneiro Dec 21 '18 at 10:18
5

If you want to sort the output by dict key you can use the collection package.

import collections
for k, v in collections.OrderedDict(sorted(d.items())).items():
    print(k, v)

It works on python 3

paolof89
  • 1,319
  • 5
  • 17
  • 31
4
>>> d={'a':1,'b':2,'c':3}
>>> for kv in d.items():
...     print kv[0],'\t',kv[1]
... 
a   1
c   3
b   2
Irshad Bhat
  • 8,479
  • 1
  • 26
  • 36
2

In addition to ways already mentioned.. can use 'viewitems', 'viewkeys', 'viewvalues'

>>> d = {320: 1, 321: 0, 322: 3}
>>> list(d.viewitems())
[(320, 1), (321, 0), (322, 3)]
>>> list(d.viewkeys())
[320, 321, 322]
>>> list(d.viewvalues())
[1, 0, 3]

Or

>>> list(d.iteritems())
[(320, 1), (321, 0), (322, 3)]
>>> list(d.iterkeys())
[320, 321, 322]
>>> list(d.itervalues())
[1, 0, 3]

or using itemgetter

>>> from operator import itemgetter
>>> map(itemgetter(0), dd.items())     ####  for keys
['323', '332']
>>> map(itemgetter(1), dd.items())     ####  for values
['3323', 232]
SuperNova
  • 25,512
  • 7
  • 93
  • 64
  • It appears these methods have been deprecated in later releases of Python 3. 3.10 does not have those methods. – Nathan Feb 28 '22 at 21:46
0

A simple dictionary:

x = {'X':"yes", 'Y':"no", 'Z':"ok"}

To print a specific (key, value) pair in Python 3 (pair at index 1 in this example):

for e in range(len(x)):
    print(([x for x in x.keys()][e], [x for x in x.values()][e]))

Output:

('X', 'yes')
('Y', 'no')
('Z', 'ok')

Here is a one liner solution to print all pairs in a tuple:

print(tuple(([x for x in x.keys()][i], [x for x in x.values()][i]) for i in range(len(x))))

Output:

(('X', 'yes'), ('Y', 'no'), ('Z', 'ok'))
Fouad Boukredine
  • 1,495
  • 14
  • 18
0

To Print key-value pair, for example:

players = {
     'lebron': 'lakers',
     'giannis':   'milwakee bucks',
     'durant':  'brooklyn nets',
     'kawhi':   'clippers',    
}

for player,club in players.items():

print(f"\n{player.title()} is the leader of {club}")

The above code, key-value pair:

 'lebron': 'lakers', - Lebron is key and lakers is value

for loop - specify key, value in dictionary.item():

Now Print (Player Name is the leader of club).

the Output is:

#Lebron is the leader of lakers
#Giannis is the leader of milwakee bucks
#Durant is the leader of brooklyn nets
#Kawhi is the leader of clippers
Raksha Saini
  • 604
  • 12
  • 28
lanreigh
  • 11
  • 1
0

If you're looking for pretty-printing a dictionary, check out Rich:

from rich import print

prices = {
    "banana": 4,
    "apple": 2,
    "orange": 1.5,
    "pear": 3,
    "strawberry": 1,
    "blueberry": 0.5,
    "mango": 4.5
}

print(prices)

enter image description here

Nico Schlömer
  • 53,797
  • 27
  • 201
  • 249