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.
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 out a dictionary nicely in Python?
I like the pprint
module (Pretty Print) included in Python. It can be used to either print the object, or format a nice string version of it.
import pprint
# Prints the nicely formatted dictionary
pprint.pprint(dictionary)
# Sets 'pretty_dict_str' to the formatted string value
pretty_dict_str = pprint.pformat(dictionary)
But it sounds like you are printing out an inventory, which users will likely want shown as something more like the following:
def print_inventory(dct):
print("Items held:")
for item, amount in dct.items(): # dct.iteritems() in Python 2
print("{} ({})".format(item, amount))
inventory = {
"shovels": 3,
"sticks": 2,
"dogs": 1,
}
print_inventory(inventory)
which prints:
Items held:
shovels (3)
sticks (2)
dogs (1)
Printing dictionary keys based on multiple value conditions
Try this code
my_dict = {'Stock A': (100, 0.5), 'Stock B': (20, 0.9), 'Stock C': (40, 0.75), 'Stock D': (45, 0.3)}
new={}
for (stock,values) in my_dict.items():
first=values[0]
second=values[1]
if (first>30 and second<0.6):
new[name]=(first,second)
Hope it helps
Print dictionary with multiple values seperated
you can use 2 for loops to first iterate on keys and value (dictionary) and the 2nd one to iterate on the set (dictionary values).
mydict = {'bob': {"flying pigs"}, 'sam':{"open house", "monster dog"}, 'sally':{"glad smile"}}
for key, value in mydict.items():
for item in value:
print(key, item, sep=', ')
Output:
bob, flying pigs
sam, open house
sam, monster dog
sally, glad smile
Python, how to print dictionary key and its values in each line?
You could do it with a single for loop
unpacking a value list each iteration.
d = {1: [2, 3], 2: [4, 5]}
for k in d:
x, y = d[k]
print("{} : {}\n{} : {}".format(k, x, k, y))
1 : 2
1 : 3
2 : 4
2 : 5
Because the value lists have just a couple numbers, it can also be done, like so:
for k, v in d.items():
print("{} : {}\n{} : {}".format(k, v[0], k, v[1]))
Related Topics
What's a Good Equivalent to Subprocess.Check_Call That Returns the Contents of Stdout
Python Ungzipping Stream of Bytes
Differencebetween Exec_Command and Send with Invoke_Shell() on Paramiko
How to Add Hours to Current Time in Python
How to "Zip Sort" Parallel Numpy Arrays
Overwriting File in Ziparchive
Removing Entries from a Dictionary Based on Values
Python Argparse Ignore Unrecognised Arguments
How to Get a Single Result from a SQL Query in Python
Is There a Recursive Version of the Dict.Get() Built-In
How to Rotate a Matplotlib Plot Through 90 Degrees
How to Plot Normal Distribution
How to Combine Python Asyncio with Threads
What Does "\R" Do in the Following Script
Does Flask Support Regular Expressions in Its Url Routing
Add Column with Number of Days Between Dates in Dataframe Pandas