Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

How do you print a dictionary value in Python?

Print a dictionary line by line using for loop & dict. items() dict. items() returns an iterable view object of the dictionary that we can use to iterate over the contents of the dictionary, i.e. key-value pairs in the dictionary and print them line by line i.e.

How do I find a key-value pair in Python?

To check if a key-value pair exists in a dictionary, i.e., if a dictionary has/contains a pair, use the in operator and the items() method. Specify a tuple (key, value) . Use not in to check if a pair does not exist in a dictionary.

Which method returns the key-value pairs in a dictionary?

items() This method returns a list of a dictionary's key-value pairs.


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

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'

Or, for Python 3:

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

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)


for key, value in d.iteritems():
    print key, '\t', value

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


>>> d={'a':1,'b':2,'c':3}
>>> for kv in d.items():
...     print kv[0],'\t',kv[1]
... 
a   1
c   3
b   2