How do I print the key-value pairs of a dictionary in python
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
How to print Specific key value from a dictionary?
It's too late but none of the answer mentioned about dict.get() method
>>> print(fruit.get('kiwi'))
2.0
In dict.get()
method you can also pass default value if key not exist in the dictionary it will return default value. If default value is not specified then it will return None
.
>>> print(fruit.get('cherry', 99))
99
fruit
dictionary doesn't have key named cherry
so dict.get()
method returns default value 99
How to print a dictionary's key?
A dictionary has, by definition, an arbitrary number of keys. There is no "the key". You have the keys()
method, which gives you a python list
of all the keys, and you have the iteritems()
method, which returns key-value pairs, so
for key, value in mydic.iteritems() :
print key, value
Python 3 version:
for key, value in mydic.items() :
print (key, value)
So you have a handle on the keys, but they only really mean sense if coupled to a value. I hope I have understood your question.
Return first N key:value pairs from dict
There's no such thing a the "first n" keys because a dict
doesn't remember which keys were inserted first.
You can get any n key-value pairs though:
n_items = take(n, d.items())
This uses the implementation of take
from the itertools
recipes:
from itertools import islice
def take(n, iterable):
"""Return the first n items of the iterable as a list."""
return list(islice(iterable, n))
See it working online: ideone
For Python < 3.6
n_items = take(n, d.iteritems())
Print the dict with “key: value” pairs in a for loop
You should instead be using dict.items
instead, since dict.keys
only iterate through the keys, and then you're printing dict.values()
which returns all the values of the dict
.
spam = {'color': 'red', 'age': '42','planet of origin': 'mars'}
for k,v in spam.items():
print(str(k)+': ' + str(v))
Turning Key, Value pairs from a Dictionary into strings
Here you go. Simply iterate the key, value pairs and format your template.
mydict = {'a':'1', 'b':'2'}
for key, value in mydict.items():
print('{} is in {}'.format(key, value))
Output:
a is in 1
b is in 2
If you would like to get a list of formated strings just do:
mylist = ['{} is in {}'.format(key, value) for key, value in mydict.items()]
mylist
will be ['a is in 1', 'b is in 2']
.
Related Topics
Difference Between Pygame.Display.Update and Pygame.Display.Flip
Are Sets Ordered Like Dicts in Python3.6
Correct Style for Python Functions That Mutate the Argument
SchröDinger's Variable: the _Class_ Cell Magically Appears If You'Re Checking for Its Presence
How to Create an Object for a Django Model with a Many to Many Field
How to Isolate Everything Inside of a Contour, Scale It, and Test the Similarity to an Image
Trying to Delay a Specific Function for Spawning Enemy After a Certain Amount of Time
Python: Sort Function Breaks in the Presence of Nan
How to Set Xlim and Ylim for a Subplot in Matplotlib
What's the Best Way to Duplicate Fork() in Windows
Text Box with Line Wrapping in Matplotlib
Is There a Module for Balanced Binary Tree in Python's Standard Library
Importerror: No Module Named <Something>
Removing Horizontal Lines in Image (Opencv, Python, Matplotlib)
Reference Requirements.Txt for the Install_Requires Kwarg in Setuptools Setup.Py File