×

Python Dictionary

Dictionary in Python is an unordered collection of data values, which is used to store data values like a map. Unlike different data types that hold just individual assets as a component, Dictionary holds the key: value pair. Key: Value is given in the Dictionary to make it more advanced and useful.

It is generally used when we have a large amount of data. It is a necessary to know the key to restoring its value. A dictionary key can be almost any Python data (except a list) but is usually preferred as a number or string. Dictionaries are defined in braces, with each item separated by key: value. In one Dictionary, we can have different types of keys and values. Word recommendations are advanced to recover values when the key is known. Python dictionary gives us many other interesting strategies assisting us while performing tasks.

Example

      d={1:"abc",2:"xyz","pqr:10"}

Creating a dictionary in python

Creating a dictionary is simple: just putting data inside curly braces {} separated by commas. A data has a key and values; while the qualities can be of any data or information type and can review, keys should be of unchanging kind (string, number, or tuple with permanent components) and should be exceptional.

NOTE: Dictionary keys are case sensitive, a similar name yet various key occurrences will be dealt with particularly.

#creating an empty dictionary

d1=dict{}

This is how we can create an empty dictionary.

Example

info = {'name': 'Md Shibbu', 'age': 19, 'location': 'Noida'}
print(info)
print(type(info))

Output

Dictionary in python

Example 2

k = ['rupees', 'pencils', 'copies', 'mugs'];
v = [13, 4, 39, 7];
items = dict(zip(k, v))
print(items)

Output

Dictionary in python

Addicting elements to a dictionary

In Python Dictionary, the extension of components should be possible in more than one way. Each value, in return, can be added to a Dictionary by identifying values alongside the key, for example, Dict[Key] = 'Value'. Settled key values can also be added to a current Dictionary. Refreshing a current value in a Dictionary should be possible using the implicit update() method.

Example

d = {'India':200,'Nepal':300,'Bhutan':400}
print("Country Name",d)
d.update({'India':500})
print("updated country name",d)

Output

Dictionary in python

Example 2

d = {'Shyam':200,'Rahul':300,'Rohit':400}
print("Name",d)
d.update({'Rahul':600,'Rohit':900})
print("updated name",d)

Output

Dictionary in python

NOTE: If the key is already present, the current value gets refreshed. A new (Key: value) match is added to the Dictionary if the key is absent.

Removing an element from a dictionary in python

We know that Dictionary is mutable; we can eliminate a specific thing in a dictionary using the pop() method. This method eliminates a thing with the given key and returns the value. The pop item() method can eliminate and return a changeable (key, value) thing pair from the Dictionary. All things can be eliminated immediately by using the del() method. We can utilize the del()keyword to eliminate individual things or the whole Dictionary itself.

Example

bdict = {'a': 'anil', 'b': 'baibhav', 'c': 'crypto', 'd': 'daniel'}
print(bdict)
ae =bdict.pop('c')
print(bdict)
print('Removed element: ', ae)

Output

Dictionary in python

Example 2

bdict = {'a': 'Amir', 'b': 'Baibhav', 'c': 'crypto', 'd': 'daniel'}
print(bdict)
if "c" in bdict:
    del bdict["c"]


print("Updated Dictionary :", bdict)

Output

Dictionary in python

Methods in dictionary in python

In Python, as with strings and lists, a few implicit techniques can be appealed on word references. Now and again, the overview and word reference techniques share a similar name. In the conversation on object-oriented programming, you will see that it is completely ok for various kinds to have approached with a similar name.

clear()- Eliminate every element from the dictionary

copy()- Returns a duplicate value of the Dictionary

get() - Returns the value of determined key

items() - Returns an overview containing a tuple for each key-value pair

keys() - Returns an overview containing the Dictionary's keys

Pop() - Remove the item and stores it for future use

pop item() - Removes the last inserted key-value pair in dictionary

update() - Updates dictionary with determined key-value pairs

values() - Returns an overview of the values of the Dictionary

NOTE: The .things(), .keys(), and .values() methods really return something many refer to as a view object. A dictionary view object is like a window on the keys and values. For down-to-earth purposes, you can consider these techniques returning arrangements of the Dictionary's keys and values.

Conclusion

In Python,Lists and dictionaries are two of the most often utilized Python types. In Dictionary, data and word references are two of the most often utilized Python types. As you have seen, they have a few similarities yet differ in how their components are used. Data and word references will generally be fitting for various conditions.


Related Topics

List Index out of Range Python for Loop

The List is generally used in Python to store multiple items or elements inside one single variable. The List is ordered in nature, the List can contain the elements inside...

3 minutes read.

Algorithm for Factorial of a number in Python

What is a Factorial Number? In mathematics, the factorial of a positive integer n, denoted by n!. It is the product of all positive integers less than or equal to n. For...

3 minutes read.

Accuracy_score Function in Sklearn

A crucial stage in data science is measuring our model's performance using the appropriate metric. In this article, we will examine two methods for calculating the accuracy of your predictions:...

13 minutes read.

Python Project Ideas for Beginners

Python project ideas for beginners Advanced Python is an amazing platform to grow and achieve success as a developer in the future. Python is a programming language that can be very...

7 minutes read.

Sklearn in Python

Scikit-learn or sklearn is a machine learning library used in Python that provides many unsupervised and supervised learning tools and algorithms. David Cournapeau first created it as a 2007 Google...

7 minutes read.

Convert Float to Int in Python using Pandas

Introduction To play with huge amounts of data, in python we require a tool. The tool which is available in Python is pandas. A panda is an open-source library. It is...

4 minutes read.

Cursor in Python

The cursor is an item that aids in query execution and records retrieval from databases. The cursor is crucial to the execution of the query. In-depth information on the execution...

7 minutes read.

Python Breakpoint

Introduction In Python 3.7, a brand-new created function called breakpoint() was added. Due to the close relationship between both the executable and the code of a debugging component, debugging Python programming...

4 minutes read.

Python List reverse() method

 Python List reverse() method The list.reverse () method in Python reverses the elements of the list in place. Syntax list.reverse() Parameter NA Example 1 # Python program explaining # the list.reverse() method weekList = ['Sun','Thurs','Mon','Fri', 'Tues', 'Wed'] print("Actual week list: ",weekList) #...

1 minute read.

Best Python AI Projects

Artificial consciousness is advancing quickly, from Chabot's to self-driving vehicles. Because of the various advantages and development presented by AI, numerous enterprises have begun searching for AI-fueled applications. Thus, there...

7 minutes read.

Python List

The list is one of the most versatile, mutable data-structures in Python. It can store heterogeneous data or different types of data. The list contains comma-separated values (item) within the square brackets. Creating...

4 minutes read.

Python Set add() Method

Python Set add() Method The set.add() method adds the specified element to a set. If the element is already present in the set, it doesn't add it. Syntax set.add(element) Parameter element- This parameter represents the element that...

1 minute read.

Python vs HTML

Python and HTML are not comparable since they are two separate categories of programming languages. Building the structures and layouts of a web page or app requires the usage of HTML,...

8 minutes read.

Python Graph

Python Graph: In Computer Science and Mathematics, a Graph is a pictorial representation of a group of objects or elements where some elements are connected using the links. A graph...

5 minutes read.

Write Text files in Python

Let's discuss writing the text file in detail. Generally, writing text also follows the same procedure as like reading text. It varies only in some specific places. Steps followed for writing...

4 minutes read.

Python program to count and display vowels in a string

Python program to count and display vowels in a string This python program counts the vowels in a string and displays them on the screen. We can do this in several...

2 minutes read.

Rank Based Percentile GUI Calculator using Tkinter in Python

GUI: The user is provided with information using manipulable visual widgets that don't require command-line input. These interface components respond to the user's interactions per the pre-programmed script, assisting each user's...

3 minutes read.

Python Scikit-image | Image Processing Using Scikit-Image

What is Image Processing? The world is defined with images and, every image has its different specialties. An image can contain much-needed information that can be helpful in various ways. The process...

4 minutes read.

Python Control Statements

Control statements are under the roof topic of loops and loops in python are defined as iteratively and repeatedly working on source code. Loop control statements are defined as they...

3 minutes read.

Idle python download for Windows

Here, we will be discussing how to get the answer to all questions related to installing Python on Windows. What is IDLE? Integrated Development and Learning Environment, or IDLE, is a shorthand....

3 minutes read.