How to create dictionary in python
source link: https://www.pythoncentral.io/how-to-create-dictionary-in-python/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
How to create dictionary in python
Content
Today we will get more into how to create a dictionary in Python. It requires that you already have basic knowledge of Python syntax. Go check our introduction to python usage to know more about Python. You need to have Python installed in your machine. To know how to install python on your system check our installation guide.
- What is the dictionary data structure
- Create a dictionary in Python
- Python dictionary usage
What is the dictionary data structure
Python dictionary is a key-value pair data structure. Each key has a single value. The key must be unique to avoid the collision. Dictionary is heavily used in python applications. If you have students and classes and each student has a class. Python dictionary will help you define the student name as a key and the class as a value. It will help you know the student course from his name value.
Dictionaries are the hash table implementation in Python. Hash table uses a hash function to map the key to its value. Each slot can store one entry. It's the same as the python dictionary did. The image below explains how it works.
We used Python dictionaries to retrieve the value if we knew it's key. The same as we did in the above student's example. Behind the scene What python does is reserve a memory place with a key and point to its value. It helps with memory optimization and efficiency. Now let's create a python dictionary.
Create a dictionary in Python
To define a Python dictionary you should define it between curly brackets ex: {}. To Assign the value to it's key you should add columns.
data = {"key": "value"}
continuing with the student's courses example Let's check how we can implement this:
class_data = { "sam": "Intro to Python", "Jack": "Intro to data science", "Emma": "Machine Learning course", "Wattson": "Web development." }
The Class dictionary has students' names. Each name has the course he enrolled in. This is a very basic and simple example of creating a python dictionary. We need to know how to use a python dictionary to insert, delete, retrieve values from it.
We mentioned that it's a key-value store. This means that to get the item value you need to know it's key. To get Jack course from the class dictionary you need to do:
print(class_data['Jack']) # output "Intro to data science"
What if the key is not in the dictionary. In such a case Python will raise a key error exception.
class_data['holo'] # ourtput KeyError Traceback (most recent call last) <ipython-input-4-73376fec291d> in <module>() ----> 1 class_data['holo'] KeyError: 'holo'
You need to handle this exception using the try/catch block. There is another more safe way to access dictionary data without raising an exception if it does not exist.
print(class_data.get('hoho', None)) # output None
The get() methods provide an easy way to check if the key exists in the dictionary. It'll return it else it'll provide a default value. This approach lets you always provide a default value if the key is missing. Now Let's insert data into our dictionary.
# add new key and value to dictionary. class_data['new_student'] = 'Ronaldo' print(class_data) # output { 'Emma': 'Machine Learning course', 'Jack': 'Intro to data science', 'Wattson': 'Web development.', 'sam': 'Intro to Python', 'new_student' : 'Ronaldo' }
You can set the value of any key to none by updating it like above. You can delete the item key and value form the dictionary using the pop() function.
class_data.pop('new_student') # output 'Ronaldo' print(class_data) # output { 'Emma': 'Machine Learning course', 'Jack': 'Intro to data science', 'Wattson': 'Web development.', 'sam': 'Intro to Python' }
Python provides a function to delete all dictionary items. Using the clear() function, you can all dictionary items.
class_data.clear() print(class_data) # output {}
In the next section, we will talk more about the usage of the Python dictionary with some tips.
Python dictionary usage
Dictionary keys and values can be any value type. You can create a key and make its value a dictionary or an array. Some of the dictionary usage in real-world examples is nested dictionaries. check the example below.
school = { "students":[ { "id": "1", "name": "Sam", "classes" : ["Web development"] }, { "id": "2", "name": "Clark", "classes" : ["Machine learning", "Data science"] }, { "id": "3", "name": "Watson", "classes" : ["Game development"] } ], "teachers":[ { "id": "1", "name": "Emma", "Courses" : ["Data science", "Machine learning"] }, { "id": "2", "name": "Jack", "Courses" : ["Game development", "Web development"] } ], "staff": [ { "id": "1", "name": "Jo", "Profission" : "Office admin" }, { "id": "2", "name": "Raj", "Profission" : "Cleaning" }, { "id": "3", "name": "Ronald", "Profission" : "sales" } ] }
Let's explain the above code. We have a school, that has teachers, students, and staff. Each one has a name and ID. The student will have a class that he enrolled in. The Student can be enrolled in multiple courses. Teachers have Courses that he teaches them to students. The school staffs have a name and profession. It's a single profession per user.
This is a simple design for school data arranged in the Python dictionary. If you're the system manager and you need to get the name and class of each student. Using for loop Python statement. You can do this:
# get all students students = school['students'] for student in students: print("Studnet name: {0} is enrolled in classes: {1}".format(student['name'], student['classes'])) # output Studnet name: Sam is enrolled in classes: ['Web development'] Studnet name: Clark is enrolled in classes: ['Machine learning', 'Data Science'] Studnet name: Watson is enrolled in classes: ['Game development']
This will get all the student's data. If You want to update student's data to add a new student all you need to do is add a new key and it's value.
students = school['students'] # add student dictionary to students list. students.append({ "id": "4", "name": "Holmes", "classes" : ["Web development"] }) print(students) # output [ { "id": "1", "name": "Sam", "classes" : ["Web development"] }, { "id": "2", "name": "Clark", "classes" : ["Machine learning", "Data science"] }, { "id": "3", "name": "Watson", "classes" : ["Game development"] }, { "id": "4", "name": "Holmes", "classes" : ["Web development"] } ]
You appended a new student dictionary to the student's list. You can do the same logic to teachers and staff too.
conclusion
Python dictionary is a very powerful data structure. It has a lot of usages. It's the flexibility to add any key and value types makes it easy to use in different applications. You can easily update and delete data from the Python dictionary easily using its functions. Working with dictionaries in python is a very important skill you need to have. It'll get you out of a lot of problems. If you're interested to know more about its implementation you can check the official documentation.
Recommend
-
49
Python offers a variety of data structures to hold our information — the dictionary being one of the most useful. Python dictionaries quick, easy to use, and flexible. As a beginning programmer, you can use this Python tu...
-
39
Learning a language is easy. Whenever I start with a new language, I focus on a few things in below order, and it is...
-
26
Dict Parser Create fast parsers to match dictionary keys. Succeeds with the longest matching key. Is stack safe. The problem If you need a parser to match strings that you know beforeha...
-
25
Introduction Due to the dynamic typing nature of Python, Python’s dict serves as a good container for passing a variety of values of different types to functions. The key of dict co...
-
9
Let’s take a quick peek what this is in this article Python 3.9 is under active development and scheduled to be released in October this year. On Feb 26, the development team released its alpha 4 version. One of t...
-
20
Flattening, inverting, merging, filtering, and more An...
-
6
Update key-value pairs – thispointer.comThis article will discuss how to add or append new key-value pairs to a dictionary or update existing keys’ values. Table of Contents We can add/append key-value pairs to...
-
1
Afiz Posted on Jan 2...
-
0
Not FoundYou just hit a route that doesn't exist... the sadness.LoginRadius empowers businesses to deliver a delightful customer experience and win customer trust. Using the LoginRadius Identity...
-
0
Create a free data dictionary with R Have data sets scattered all over the place? Here's how to pull them into a single, robust catalog with the pointbla...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK