- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What is correct syntax to create Python dictionary?
The correct syntax to create a Python Dictionary is storing values in the form of key:value pairs. On the left of colon, we store keys and on the right, values i.e.
key:value
Dictionary is enclosed by curly bracket and do not allow duplicates. According to the 3.7 Python update, dictionaries are now ordered. Consider Dictionary as a set of key: value pairs, with the requirement that the keys are unique (within one dictionary). Each key in a Dictionary is separated from its value by a colon (:), the items are separated by commas, and the whole thing is enclosed in curly braces.
Create a Dictionary in Python with 4 key-value pairs
We will create 4 key-value pairs, with keys Product, Model, Units and Available and values Mobile, XUT, 120 and Yes. Keys are on the left of colon, whereas values are on the right −
Example
# Creating a Dictionary with 4 key-value pairs myprod = { "Product":"Mobile", "Model": "XUT", "Units": 120, "Available": "Yes" } # Displaying the Dictionary print("Dictionary = \n",myprod)
Output
Dictionary = {'Product': 'Mobile', 'Model': 'XUT', 'Units': 120, 'Available': 'Yes'}
Above, we have displayed product details in the form of Dictionaries with 4 key-value pairs.
Create a Dictionary in Python with 5 key-value pairs
We will create 5 key-value pairs, with keys Product, Model, Units, Available, Grades and values Mobile, XUT, 120, Yes, “A” −
Example
# Creating a Dictionary with 5 key-value pairs myprod = { "Product":"Mobile", "Model": "XUT", "Units": 120, "Available": "Yes", "Grades": "A" } # Displaying the Dictionary print("Dictionary = \n",myprod)
Output
Dictionary = {'Product': 'Mobile', 'Model': 'XUT', 'Units': 120, 'Available': 'Yes', 'Grades': 'A'}
Above, we have displayed product details in the form of Dictionaries with 5 key-value pairs.
Create a Dictionary in Python using the dict() method
We can also create a Dictionary using a Built-in method dict(). We have set the key:value pairs in the method itself −
Example
# Creating a Dictionary using the dict() method myprod = dict({ "Product":"Mobile", "Model": "XUT", "Units": 120, "Available": "Yes" }) # Displaying the Dictionary print("Dictionary = \n",myprod) # Display the Keys print("\nKeys = ",myprod.keys()) # Display the Values print("Values = ",myprod.values())
Output
Dictionary = {'Product': 'Mobile', 'Model': 'XUT', 'Units': 120, 'Available': 'Yes'} Keys = dict_keys(['Product', 'Model', 'Units', 'Available']) Values = dict_values(['Mobile', 'XUT', 120, 'Yes'])