The Python Oracle

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

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Melt

--

Chapters
00:00 How Do I Print The Key-Value Pairs Of A Dictionary In Python
00:20 Answer 1 Score 11
00:32 Answer 2 Score 38
00:42 Accepted Answer Score 544
01:21 Answer 4 Score 102
01:59 Thank you

--

Full question
https://stackoverflow.com/questions/2666...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #dictionary

#avk47



ACCEPTED ANSWER

Score 544


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



ANSWER 2

Score 102


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'



ANSWER 3

Score 38


Or, for Python 3:

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



ANSWER 4

Score 11


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}')