[ad_1]
How to Create Python Dictionary?
As we discuss software and languages, Python is probably one of the most commonly found words in today’s time. Although the industry experts have in-depth knowledge about it, beginners may find it a little difficult to understand the concept. This blog will discuss ways of creating a Python dictionary; however, let us first try to understand what Python is.
What is Python?
Python is a high-level, general-purpose programming language that is well-interpreted. The design philosophy of this programming language is code readability with the remarkable use of important indentation. The language of Python constructs and its object-oriented approach targets help the programmers to write logical and clear code for small as well as large-scale projects.
The programming language is dynamically-types and also garbage-collected. Several programming paradigms such as structured, object-oriented, and functional programming are supported by it. It is often described as a “batteries included” language since it has a comprehensive standard library.
Work on Python was started by Guido van Rossum in the late 1980s. It initially was started as a successor to the ABC programming language and in 1991 was first released as Python 0.9.0. In 2000, Python 2.0 was released with new features such as list comprehensions and a garbage collection system in which reference counting was used. In 2008, Python 3.0 was released. It was a huge revision of the language, which was not totally backward-compatible. Python 2 does not run unmodified on Python 3. In 2020, Python 2 was finally discontinued version 2.7.18.
Read more:- Python Tutorial
Python Dictionary
Python Dictionary is an unordered pool of data values. It is used for storing data values such as a map, which holds a single value as an element. The Python dictionary holds key-value pairs. The key value is included in the dictionary to make it better optimized.
How to Create Python Dictionary
A Python dictionary can be created by assigning a sequence of elements in curly {} braces. It is separated by ‘comma’. In a dictionary, you will find a pair of values, in which one is the Key, and the other one is the corresponding pair element, which is called the Key:value. Values that you find in a dictionary can be of various data types and even can be replicated, while the keys cannot be duplicated and must be absolute.
# Creating a Dictionary
# with Integer Keys
Dict = {1: ‘Geeks’, 2: ‘For’, 3: ‘Geeks’}
print(“nDictionary with the use of Integer Keys: “)
print(Dict)
# Creating a Dictionary
# with Mixed keys
Dict = {‘Name’: ‘Geeks’, 1: [1, 2, 3, 4]}
print(“nDictionary with the use of Mixed Keys: “)
print(Dict)
Output
Dictionary with the use of Integer Keys:
{1: ‘Geeks’, 2: ‘For’, 3: ‘Geeks’}
Dictionary with the use of Mixed Keys:
{1: [1, 2, 3, 4], ‘Name’: ‘Geeks’}
A Python dictionary can also be created with the help of the built-in function dict(). If you want to create an empty dictionary, you can place curly braces{}.
# Creating an empty Dictionary
Dict = {}
print(“Empty Dictionary: “)
print(Dict)
# Creating a Dictionary
# with dict() method
Dict = dict({1: ‘Geeks’, 2: ‘For’, 3:’Geeks’})
print(“nDictionary with the use of dict(): “)
print(Dict)
# Creating a Dictionary
# with each item as a Pair
Dict = dict([(1, ‘Geeks’), (2, ‘For’)])
print(“nDictionary with each item as a pair: “)
print(Dict)
Output
Empty Dictionary:
{}
Dictionary with the use of dict():
{1: ‘Geeks’, 2: ‘For’, 3: ‘Geeks’}
Dictionary with each item as a pair:
{1: ‘Geeks’, 2: ‘For’}
Nested Dictionary
# Creating a Nested Dictionary
# as shown in the below image
Dict = {1: ‘Geeks’, 2: ‘For’,
3:{‘A’ : ‘Welcome’, ‘B’ : ‘To’, ‘C’ : ‘Geeks’}}
print(Dict)
# Creating a Nested Dictionary
# as shown in the below image
Dict = {1: ‘Geeks’, 2: ‘For’,
3:{‘A’ : ‘Welcome’, ‘B’ : ‘To’, ‘C’ : ‘Geeks’}}
print(Dict)
Output
{1: ‘Geeks’, 2: ‘For’, 3: {‘A’: ‘Welcome’, ‘B’: ‘To’, ‘C’: ‘Geeks’}}
Adding elements to a Dictionary
You can add elements to a Python dictionary in several ways. You can add one value at a time to a dictionary by describing the value with the key.
For example, Dict[Key] = ‘Value’.
The existing value in a dictionary can be updated if you use the built-in update() method. You can also add nested key values to an existing Dictionary.
# Creating an empty Dictionary
Dict = {}
print(“Empty Dictionary: “)
print(Dict)
# Adding elements one at a time
Dict[0] = ‘Geeks’
Dict[2] = ‘For’
Dict[3] = 1
print(“nDictionary after adding 3 elements: “)
print(Dict)
# Adding set of values
# to a single Key
Dict[‘Value_set’] = 2, 3, 4
print(“nDictionary after adding 3 elements: “)
print(Dict)
# Updating existing Key’s Value
Dict[2] = ‘Welcome’
print(“nUpdated key value: “)
print(Dict)
# Adding Nested Key value to Dictionary
Dict[5] = {‘Nested’ :{‘1’ : ‘Life’, ‘2’ : ‘Geeks’}}
print(“nAdding a Nested Key: “)
print(Dict)
Output
Empty Dictionary:
{}
Dictionary after adding 3 elements:
{0: ‘Geeks’, 2: ‘For’, 3: 1}
Dictionary after adding 3 elements:
{0: ‘Geeks’, 2: ‘For’, 3: 1, ‘Value_set’: (2, 3, 4)}
Updated key value:
{0: ‘Geeks’, 2: ‘Welcome’, 3: 1, ‘Value_set’: (2, 3, 4)}
Adding a Nested Key:
{0: ‘Geeks’, 2: ‘Welcome’, 3: 1, 5: {‘Nested’: {‘1’: ‘Life’, ‘2’: ‘Geeks’}}, ‘Value_set’: (2, 3, 4)}
Accessing elements from a Dictionary
To access a Python dictionary, you can refer to its key name. You can use the key inside the square brackets.
# Python program to demonstrate
# accessing an element from a Dictionary
# Creating a Dictionary
Dict = {1: ‘Geeks’, ‘name’: ‘For’, 3: ‘Geeks’}
# accessing a element using key
print(“Accessing a element using key:”)
print(Dict[‘name’])
# accessing a element using key
print(“Accessing a element using key:”)
print(Dict[1])
Output
Accessing a element using key:
For
Accessing a element using key:
Geeks
There is another method, which is called ‘get()’. This also helps in accessing elements from a doctionary.
# Creating a Dictionary
Dict = {1: ‘Geeks’, ‘name’: ‘For’, 3: ‘Geeks’}
# accessing a element using get()
# method
print(“Accessing a element using get:”)
print(Dict.get(3))
Output
Accessing an element using get:
Geeks
Accessing an element of a nested dictionary
To access the value of key in the nested dictionary, you can use indexing [] syntax.
# Creating a Dictionary
Dict = {‘Dict1’: {1: ‘Geeks’},
‘Dict2’: {‘Name’: ‘For’}}
# Accessing element using key
print(Dict[‘Dict1’])
print(Dict[‘Dict1’][1])
print(Dict[‘Dict2’][‘Name’])
Output
{1: ‘Geeks’}
Geeks
For
How to remove elements from the dictionary?
You can delete keys in a Python dictionary with the help of the del keyword. In fact, by using the del keyword, you can delete some specific values from the dictionary or even the whole dictionary. You can also delete items in a nested dictionary by using the del keyword.
# Initial Dictionary
Dict = { 5 : ‘Welcome’, 6 : ‘To’, 7 : ‘Geeks’,
‘A’ : {1 : ‘Geeks’, 2 : ‘For’, 3 : ‘Geeks’},
‘B’ : {1 : ‘Geeks’, 2 : ‘Life’}}
print(“Initial Dictionary: “)
print(Dict)
# Deleting a Key value
del Dict[6]
print(“nDeleting a specific key: “)
print(Dict)
# Deleting a Key from
# Nested Dictionary
del Dict[‘A’][2]
print(“nDeleting a key from Nested Dictionary: “)
print(Dict)
Output
Initial Dictionary:
{‘A’: {1: ‘Geeks’, 2: ‘For’, 3: ‘Geeks’}, ‘B’: {1: ‘Geeks’, 2: ‘Life’}, 5: ‘Welcome’, 6: ‘To’, 7: ‘Geeks’}
Deleting a specific key:
{‘A’: {1: ‘Geeks’, 2: ‘For’, 3: ‘Geeks’}, ‘B’: {1: ‘Geeks’, 2: ‘Life’}, 5: ‘Welcome’, 7: ‘Geeks’}
Deleting a key from Nested Dictionary:
{‘A’: {1: ‘Geeks’, 3: ‘Geeks’}, ‘B’: {1: ‘Geeks’, 2: ‘Life’}, 5: ‘Welcome’, 7: ‘Geeks’}
Using pop() method
You can use the pop() method to return as well as delete the value of the specified key.
# Creating a Dictionary
Dict = {1: ‘Geeks’, ‘name’: ‘For’, 3: ‘Geeks’}
# Deleting a key
# using pop() method
pop_ele = Dict.pop(1)
print(‘nDictionary after deletion: ‘ + str(Dict))
print(‘Value associated to poped key is: ‘ + str(pop_ele))
Output
Dictionary after deletion: {3: ‘Geeks’, ‘name’: ‘For’}
Value associated to poped key is: Geeks
Using popitem() method
To remove an arbitrary element (key, value) pair from the dictionary, you can use the popitem().
# Creating Dictionary
Dict = {1: ‘Geeks’, ‘name’: ‘For’, 3: ‘Geeks’}
# Deleting an arbitrary key
# using popitem() function
pop_ele = Dict.popitem()
print(“nDictionary after deletion: ” + str(Dict))
print(“The arbitrary pair returned is: ” + str(pop_ele))
Output
Dictionary after deletion: {3: ‘Geeks’, ‘name’: ‘For’}
The arbitrary pair returned is: (1, ‘Geeks’)
Using clear() method
You can actually delete all the items in the dictionary by using clear()
# Creating a Dictionary
Dict = {1: ‘Geeks’, ‘name’: ‘For’, 3: ‘Geeks’}
# Deleting entire Dictionary
Dict.clear()
print(“nDeleting Entire Dictionary: “)
print(Dict)
Output
Deleting Entire Dictionary:
{}
If you want to learn Python for free, you can refer to Great Learning. Apart from Python, there are several other courses as well that you can do through Great Learning. Some of the courses that you can opt for are Artificial Intelligence & Machine Learning, Data Science & Business Analytics, Management, Cloud Computing, Cyber Security, Software Development, Digital Marketing, Design Thinking, etc. To know more about this amazing learning platform, you can visit the website today and enquire about admission. You can give a call to the number mentioned on the website.
Read more:-
Python Interview Questions
How to run Python Script
Polymorphism in Python
0
[ad_2]
Source link