Dictionary in Python
A dictionary is a crucial knowledge kind in Python programming. It is a group of information values which are unordered. Python dictionary is used to retailer objects wherein every merchandise has a key-value pair. The dictionary is made up of those key-value pairs, and this makes the dictionary extra optimized.
For instance –
Dict = {1: 'Learning', 2: 'For', 3: 'Life'}
print(Dict)
Here,
The colon is used to pair keys with the values.
The comma is used as a separator for the weather.
The output is:
{1: ‘Learnings’, 2: ‘For’, 3: ‘Life’}
Python dictionary append is solely used so as to add key/worth to the prevailing dictionary. The dictionary objects are mutable. Unlike different objects, the dictionary merely shops a key together with its worth. Therefore, the mixture of a key and its subsequent worth represents a single component within the Python dictionary.
Restrictions on Key Dictionaries
Below are enlisted some restrictions on the important thing dictionaries –
- A given key seems solely as soon as in a dictionary. Duplicates of keys aren’t allowed.
- It gained’t make sense should you map a specific key greater than as soon as. This is so as a result of the dictionary will map every key to its worth.
- In case of a duplication of a key, the final one might be thought-about.
- If a secret is specified a second time after the creation of a dictionary, then the second time might be thought-about as it’s going to override the primary time.
- The key should be immutable, which implies that the information kind will be an integer, string, tuple, boolean, and so forth. Therefore, lists or one other dictionary cannot be used as they’re changeable.
How to append a component to a key in a dictionary with Python?
Creating a Dictionary
In Python, you’ll be able to create a dictionary simply utilizing mounted keys and values. The sequence of parts is positioned inside curly brackets, and key: values are separated by commas. It should be famous that the worth of keys will be repeated however cannot have duplicates. Also, keys ought to have immutable knowledge varieties reminiscent of strings, tuples, or numbers.
Here’s an instance –
# Creating a Dictionary
# with Integer Keys
Dict = {1: 'Learning', 2: 'For', 3: Life}
print("nDictionary with the usage of Integer Keys: ")
print(Dict)
# Creating a Dictionary
# with Mixed keys
Dict = {'Name': ‘Great Learning’, 1: [1, 2, 3, 4]}
print("nDictionary with the usage of Mixed Keys: ")
print(Dict)
The output is :
Dictionary with the usage of Integer Keys:
{1: ‘Learning’, 2: ‘For’, 3: ‘Life’}
Dictionary with the usage of Mixed Keys:
{‘Name’: ‘GreatLearning’, 1: [1, 2, 3, 4]}
Dictionary with integer keys
Here’s the best way to create a dictionary utilizing the integer keys –
# creating the dictionary
dict_a = {1 : "India", 2 : "UK", 3 : "US", 4 : "Canada"}
# printing the dictionary
print("Dictionary 'dict_a' is...")
print(dict_a)
# printing the keys solely
print("Dictionary 'dict_a' keys...")
for x in dict_a:
print(x)
# printing the values solely
print("Dictionary 'dict_a' values...")
for x in dict_a.values():
print(x)
# printing the keys & values
print("Dictionary 'dict_a' keys & values...")
for x, y in dict_a.objects():
print(x, ':', y)
The output is:
Dictionary ‘dict_a’ is…
{1: ‘India’, 2: ‘USA’, 3: ‘UK’, 4: ‘Canada’}
Dictionary ‘dict_a’ keys…
1
2
3
4
Dictionary ‘dict_a’ values…
India
USA
UK
Canada
Dictionary ‘dict_a’ keys & values…
1 : India
2 : UK
3 : US
4 : Canada
Accessing parts of a dictionary
Key names are used to entry parts of a dictionary. To entry the weather, it is advisable to use sq. brackets ([‘key’]) with the important thing inside it.
Here’s an instance –
# Python program to exhibit
# accessing a component from a dictionary
# Creating a Dictionary
Dict = {1: 'Learning', 'title': 'For', 3: 'Life'}
# accessing a component utilizing key
print("Accessing a component utilizing key:")
print(Dict['name'])
# accessing a component utilizing key
print("Accessing a component utilizing key:")
print(Dict[1])
The output is:
Accessing a component utilizing key:
For
Accessing a component utilizing key:
Life
Alternative technique
There’s one other technique known as get() that’s used to entry parts from a dictionary. In this technique, the hot button is accepted as an argument and returned with a worth.
Here’s an instance –
# Creating a Dictionary
Dict = {1: 'Learning', 'title': 'For', 3: 'Life'}
# accessing a component utilizing get()
# technique
print("Accessing a component utilizing get:")
print(Dict.get(3))
The output is:
Accessing a component utilizing get:
Life
Deleting component(s) in a dictionary
You can delete parts in a dictionary utilizing the ‘del’ key phrase.
The syntax is –
del dict['yourkey'] #This will take away the component along with your key.
Use the next syntax to delete your entire dictionary –
del my_dict # this can delete the dictionary with title my_dict
Another different is to make use of the clear() technique. This technique helps to scrub the content material contained in the dictionary and empty it. The syntax is –
Let us verify an instance of the deletion of parts that lead to emptying your entire dictionary –
my_dict = {"username": "ABC", "e mail": "abc@gmail.com", "location":"Gurgaon"}
del my_dict['username'] # it's going to take away "username": "ABC" from my_dict
print(my_dict)
my_dict.clear() # until will make the dictionarymy_dictempty
print(my_dict)
delmy_dict # this can delete the dictionarymy_dict
print(my_dict)
The output is:
{’e mail’: ‘abc@gmail.com’, ‘location’: ‘Gurgaon’}
{}
Traceback (most up-to-date name final):
File “main.py”, line 7, in <module>
print(my_dict)
NameError: title ‘my_dict’ shouldn’t be outlined
Deleting Element(s) from dictionary utilizing pop() technique
The dict.pop() technique can also be used to delete parts from a dictionary. Using the built-in pop() technique, you’ll be able to simply delete a component based mostly on its given key. The syntax is:
dict.pop(key, defaultvalue)
The pop() technique returns the worth of the eliminated key. In case of the absence of the given key, it’s going to return the default worth. If neither the default worth nor the hot button is current, it’s going to give an error.
Here’s an instance that reveals the deletion of parts utilizing dict.pop() –
my_dict = {"username": "ABC", "e mail": "abc@gmail.com", "location":"Gurgaon"}
my_dict.pop("username")
print(my_dict)
The output is:
{’e mail’: ‘abc@gmail.com’, ‘location’: ‘Gurgaon’}
Appending component(s) to a dictionary
It is simple to append parts to the prevailing dictionary utilizing the dictionary title adopted by sq. brackets with a key inside it and assigning a worth to it.
Here’s an instance:
my_dict = {"username": "ABC", "e mail": "abc@gmail.com", "location":"Gurgaon"}
my_dict['name']='Nick'
print(my_dict)
The output is:
{‘username’: ‘ABC’, ’e mail’: ‘abc@gmail.com’, ‘location’: ‘Gurgaon’, ‘name’: ‘Nick’}
Updating current component(s) in a dictionary
For updating the prevailing parts in a dictionary, you want a reference to the important thing whose worth must be up to date.
In this instance, we’ll replace the username from ABC to XYZ. Here’s the best way to do it:
my_dict = {"username": "ABC", "e mail": "abc@gmail.com", "location":"Gurgaon"}
my_dict["username"] = "XYZ"
print(my_dict)
The output is:
{‘username’: ‘XYZ’, ’e mail’: ‘abc@gmail.com’, ‘location’: ‘Gurgaon’}
Insert a dictionary into one other dictionary
Let us contemplate an instance with two dictionaries – Dictionary 1 and Dictionary 2 as proven beneath –
Dictionary 1:
my_dict = {“username”: “ABC”, “email”: “abc@gmail.com”, “location”:”Gurgaon”}
Dictionary 2:
my_dict1 = {“firstName” : “Nick”, “lastName”: “Jonas”}
Now we need to merge Dictionary 1 into Dictionary 2. This will be achieved by making a key known as “name” in my_dict and assigning my_dict1 dictionary to it. Here’s the best way to do it:
my_dict = {"username": "ABC", "e mail": "abc@gmail.com", "location":"Gurgaon"}
my_dict1 = {"firstName" : "Nick", "finalName": "Jonas"}
my_dict["name"] = my_dict1
print(my_dict)
The output is:
{‘username’: ‘ABC’, ’e mail’: ‘abc@gmail.com’, ‘location’: ‘Gurgaon’, ‘name’: {‘firstName’: ‘Nick’, ‘lastName’: Jonas}}
As noticed within the output, the important thing ‘name’ has the dictionary my_dict1.
FAQs
Yes, you’ll be able to append to a dictionary in Python. It is completed utilizing the replace() technique. The replace() technique hyperlinks one dictionary with one other, and the strategy entails inserting key-value pairs from one dictionary into one other dictionary.
You can add knowledge or values to a dictionary in Python utilizing the next steps:
First, assign a worth to a brand new key.
Use dict. Update() technique so as to add a number of values to the keys.
Use the merge operator (I) if you’re utilizing Python 3.9+
Create a customized operate
Yes, append works for dictionaries in Python. This will be achieved utilizing the replace() operate and [] operator.
To append to a dictionary key in Python, use the next steps:
1. Converting an current key to an inventory kind to append worth to that key utilizing the append() technique.
2. Append an inventory of values to the prevailing dictionary’s keys.
Appending an empty dictionary means including a key-value pair to that dictionary. This will be achieved utilizing the dict[key] technique.
Here’s the best way to do it:
a_dict = {}
a_dict[“key”] = “value”
print(a_dict)
The output is:
{‘key’: ‘value’}
Using the replace() operate and [] operator, you’ll be able to add or append a brand new key-value to the dictionary. This technique may also be used to exchange the worth of any current key or append new values to the keys.