What is a Python Dictionary?
Dictionaries are a data structure in the Python implementation that is more generally known as an associative array.
A Python dictionary consists of a collection of key-value pairs.
Each key-value pair maps the key to its associated value.
Python Dictionary Methods
Here are different dictionary methods which surely you can utilize.
Python Dictionary Method | Description |
clear() | Removes all items from the dictionary. |
copy() | Returns a shallow copy of the dictionary. |
formkeys(seq[,v]) | Returns a new dictionary with the key from seq and value equal to v (defaults to None ) |
get(key[,d]) | Returns the value of the key . If the key does not exist, returns d (defaults to None ) |
items() | Return a new object of the dictionary items in (key, value) format. |
keys() | Returns a new object of the dictionary key. |
pop(key[,d]) | Removes the item with the key and returns its value, or d if the key is not found. If d is not provided and the key is not found, it raises KeyError . |
popitem() | Removes and returns an arbitrary item (key, value). If the dictionary is empty, it raises KeyError . |
setdefault(key[,d]) | Returns the corresponding value if the key is in the dictionary. If not, inserts the key with a value of d and returns d (defaults to None ). |
update([other]) | Updates the dictionary with the key/value pairs from other , overwriting existing keys. |
values() | Returns a new object of the dictionary’s values. |
Dictionary Built-in Functions in Python
The table shown below shows the Python dictionary’s built-in functions like all(), any(), len(), cmp(), sorted(), etc., which are commonly used to perform different tasks.
Python Dictionary Built-in Function | Description |
all() | Return True if all keys of the dictionary are True (or if the dictionary is empty). |
any() | Return True if any key of the dictionary is true. If the dictionary is empty, return False . |
len() | Return the length (the number of items) in the dictionary. |
cmp() | Compares items of two dictionaries |
sorted() | Return a new sorted list of keys in the dictionary. |
How to Print Dictionary in Python?
The simplest and most straightforward way to print a dictionary is by utilizing the built-in print() function.
Bypassing the dictionary as an argument, the function automatically outputs its contents to the console.
Let’s consider an example:
thisdict = {
"Name": "Angel Jude",
"Age": 26,
"Position": "Programmer"
}
print(thisdict)
When you execute the program, this will be the output:
{‘Name’: ‘Angel Jude’, ‘Age’: 26, ‘Position’: ‘Programmer’}
Python Dictionary Items
The Dictionary items are ordered, changeable, and do not allow duplicates.
Dictionary items are presented in key: value pairs and can be referred to by using the key name.
Here’s an example of how to print the value of a dictionary item.
thisdict = {
"Name": "Angel Jude",
"Age": "26",
"Position": "Programmer"
}
print(thisdict["Position"])
When you execute the program, this will be the output:
Programmer
Python Print Dictionary: Advanced Techniques
Now that we’ve covered the basics of printing dictionary elements, let’s explore some advanced techniques and methods that can further enhance your Python programming skills.
Sorting Dictionary Keys
When working with large dictionaries, it can be beneficial to sort the keys in a specific order before printing the dictionary.
The sorted()
function allows us to achieve this easily.
Consider the following example:
my_dict = {'name': 'Ray', 'age': 25, 'country': 'USA'}
for key in sorted(my_dict.keys()):
print(f"{key}: {my_dict[key]}")
Output:
age: 25
country: USA
name: Ray
By applying the sorted() function to the dictionary’s keys, we ensure that the keys are printed in alphabetical order.
This technique can be particularly useful when presenting data in a more organized manner.
Conditional Printing
In certain scenarios, you may want to print specific dictionary elements based on certain conditions.
Python provides the ability to incorporate conditional statements within the print function to achieve this.
Let’s consider an example:
my_dict = {'name': 'Ray', 'age': 35, 'country': 'USA'}
for key, value in my_dict.items():
if key == 'age' or key == 'country':
print(f"{key}: {value}")
Output:
age: 35
country: USA
By incorporating an if statement, we can selectively print only the dictionary elements that meet the specified conditions.
This technique allows for greater flexibility when displaying specific information from a dictionary.
Summary
In this tutorial, we have completely discussed how to print a dictionary in Python in a different function, which we learned with the help of examples.
I hope this simple Python tutorial helped you a lot to comply with your requirements.
Inquiries
If you have any questions or suggestions about this simple tutorial, “How Python Print Dictionary with Examples,” please feel free to comment below. Thank You!