We can help you develop your capabilities until you achieve your dream

Digital marketing

What It Is & How to Create One

Python is a programming language with many tools and features. One such feature is the dictionary. A dictionary in Python is a collection of key-value pairs. The dictionary keys must be unique. The dictionary value may be of any type. In this blog post, we’ll explore the dictionary in Python and learn how to use it.

What Is Dictionary in Python?

A dictionary is a kind of data structure that stores items in key-value pairs. A key is a unique identifier for an item, and a value is the data associated with that key. Dictionaries often store information such as words and definitions, but they can be used for much more. Dictionaries are mutable in Python, which means they can be changed after they are created. They are also unordered, indicating the items in a dictionary are not stored in any particular order.

How to Create a Dictionary in Python?

Dictionaries are created using curly braces {}. The key is on the left side of the colon (:) and the value is on the right. A comma separates each key-value pair. Creating a Python dictionary is straightforward. Remember to use curly braces {} and separate each key-value pair with a comma.

You will use the built-in dictionary data type to create a Python dictionary. This type stores all kinds of data, from integers to strings to lists. The dictionary data type is similar to a list but uses keys instead of indexes to look up values.

You use the dict() function in Python to create a dictionary. This function takes two arguments:

The first argument is a list of keys.

The second argument is a list of values.

Check out the example of how to create a dictionary using the dict() function:

# empty dictionary
my_dict = {}
# dictionary with integer keys
my_dict = {1: 'apple', 2: 'ball'}
# dictionary with mixed keys
my_dict = {'name': 'John', 1: [2, 4, 3]}
# using dict()
my_dict = dict({1:'apple', 2:'ball'})
# from sequence having each item as a pair
my_dict = dict([(1,'apple'), (2,'ball')])

Image Reference

Complexities for Creating a Dictionary

The time complexity of a dictionary is O(len(dict)); because a dictionary must be created, the hash function must calculate the hash values for each element. O(N) is the space complexity required to create a dictionary.

Changing and Adding Elements to a Dictionary

In Python, dictionaries are mutable data structures that allow you to store key-value pairs. Dictionary can be created using the dict() constructor or curly braces’ {}’. Once you have created a dictionary, you can add, remove, or update elements using the methods dict.update(), dict.pop(), and dict.popitem().

The `dict.update()` method is used to change an element in a dictionary. This method takes a key and a value as arguments and assigns the value to the key. It will be added if the key does not exist in the dictionary.

You can use the `dict.pop()` method to remove an element from a dictionary. This method takes a key value as an argument and removes the key-value pair from the dictionary. In case when key does not exist in the dictionary, `dict.pop()` will raise a `KeyError.`

The dict.popitem()` method is used to remove an arbitrary element from a dictionary, . This method removes a random key-value pair from the dictionary and returns it as a tuple. If the dictionary is empty, `dict.popitem()` will raise a `KeyError`.

Accessing Elements of a Dictionary

In Python, dictionaries are accessed by key, not by index. This means you can’t access a dictionary element by using its position in the dictionary. Instead, you must use the dictionary key.

There are two ways to access a dictionary element in Python. The first is by using the get() method. This method takes two arguments: the dictionary key and a default value. If the key is in the dictionary, the get() method will return the value associated with that key. The get() method will return the default value if the key is not in the dictionary.

The second way to access a dictionary element is using the [] operator. This operator takes the dictionary key as an argument and returns the value associated with the key value. If the key value is not in the dictionary, the [] operator will raise a KeyError.

# get vs [] for retrieving elements
my_dict = {'name': 'Jack', 'age': 26}
# Output: Jack
print(my_dict['name'])
# Output: 26
print(my_dict.get('age'))
# Trying to access keys that don't exist throws an error
# Output None
print(my_dict.get('address'))
# KeyError
print(my_dict['address'])​

Image Reference

Methods

In Python, several built-in methods allow us to manipulate dictionaries. These methods are useful for adding, removing, and changing the values of dictionary keys. Dictionary methods are a powerful way to work with dictionaries. By understanding how these methods work, we can more effectively use dictionaries to store and manipulate data.

Method

Description

clear()

Removes all the elements from the dictionary

copy()

Returns a copy of the dictionary

get()

Returns specified key value

items()

Returns an index having a tuple for every key-value pair

keys()

Returns a list containing the dictionary’s keys

pop()

Removes the element with the specified key

popitem()

Remove last inserted key-value pair

setdefault()

Returns specified key value. If a key value does not exist: insert the specified value of key

fromkeys()

Returns specified keys and values in dictionary

update()

Updates the specified key-value pairs in dictionary

values()

Returns values lists in the dictionary

Python Dictionary Comprehension

Dictionary comprehension is a feature that allows you to create a dictionary from a list or another dictionary in a single line of code. It is a very concise way of creating dictionaries and can be used to perform various operations on dictionaries. The expression of Dictionary comprehension is (key: value) followed by a for statement within the curly braces {}.

# Dictionary Comprehension

squares = {x: x*x for x in range(6)}

print(squares)
​

Dictionary Built-in Functions

Dictionaries have several built-in functions that allow you to perform various operations on them. all(), any(), len(), cmp(), sorted(), etc. are the most common dictionaries functions.

Function

Description

all()

The all() function in the python dictionary checks if all the keys in the dictionary have True as their values. If all the values are True, then it returns True. Otherwise, it returns False.

any()

The any() function on python dict checks if any of the values in the dict are True. If any of the values are True, it returns True, otherwise, it returns False.

cmp()

The cmp() function is used to compare two dictionaries by key. The function gives a negative value if the first dictionary is lesser than the second dictionary, a positive value if the first dictionary is greater than the second dictionary, and 0 if the two dictionaries are equal.

sorted()

This function is used to sort a dictionary in Python. The function takes two arguments: the dictionary to be sorted and the key on which the sorting will be based. The key can be a function, a list, or a tuple. The function returns a list of tuples, with each tuple consisting of the key and the value.

len()

It is a built-in function that returns the length of an object. It can be used on various objects such as strings, lists, dictionaries, etc.

Python Dictionary keys() Method

The keys() method in Python dictionary returns a view object that displays all the keys in the dictionary. View objects have some similar properties to the dictionary they are defined in. For example, you can iterate through a view object to print all the keys in the dictionary. It is possible to check if a key exists in a view object.

numbers = {1: 'one', 2: 'two', 3: 'three'}
# extracts the keys of the dictionary
dictionary keys = numbers.keys()
print(dictionaryKeys)
# Output: dict_keys([1, 2, 3])
​

Image Reference

Python Dictionary Values() Method

The values() method returns a view object that displays a list of all the values in the dictionary.

You can get the list of all the values in the dictionary using the values() method. The view object will reflect any changes made to the dictionary, so if you add or delete values from the dictionary, the view object will also update. The values() method differs from the keys() method because it doesn’t take any arguments.

Check out the example on how to use the values() method in Python:

marks = {'Physics':67, 'Maths':87}

print(marks.values())

# Output: dict_values([67, 87])
​

Image Reference

Conclusion

Python is a great language that comes with many different features. It offers a structured code, making it easier to understand. With Python being one of the most prominent programming languages in today’s day and age, it is important to have a thorough understanding of this programming language. Simplilearn’s Python Training certification course is the best Python course to help you understand Python basics and other core concepts. It offers hands-on development experience and prepare you for an exciting career as a professional Python programmer.

FAQs

  1. How to sort a dictionary in Python?

To sort a dictionary in Python based on its keys or values, you can use the sorted() function along with a lambda function or a custom key function. For example, to sort by keys:

sorted_dict = dict(sorted(my_dict.items()))

, and to sort by values:

sorted_dict = dict(sorted(my_dict.items(), key=lambda item: item[1]))

2. How to convert a list to a dictionary in Python?

You can convert a list to a dictionary in Python using list comprehension or the zip() function. For example,

 my_list = ['a', 'b', 'c']

can be converted to a dictionary with keys and values:

my_dict = {key: value for key, value in enumerate(my_list)}.

3. How to append a dictionary in Python?

To append or add elements to a dictionary in Python, you can directly assign a new key-value pair, or use the

update()

method to merge another dictionary into the existing one. For example,

my_dict['new_key'] = 'new_value' or my_dict.update({'new_key': 'new_value'})

4. How to iterate dictionaries in Python?

You can iterate through a dictionary in Python using a for loop, accessing keys, values, or key-value pairs. For example, to iterate through keys:

 for key in my_dict.keys()

, through values:

for value in my_dict.values()

, or through key-value pairs:

for key, value in my_dict.items().

5. How to add elements in a dictionary in Python?

To add elements to a dictionary in Python, you can directly assign a new key-value pair using the subscript notation. For example,

my_dict['new_key'] = 'new_value'

If the key already exists, its value will be updated; otherwise, a new key-value pair will be added.

6. How to convert string to dictionary in Python?

To convert a string to a dictionary in Python, you can use the

json.loads()

 function if the string is in JSON format. Otherwise, if the string follows a specific key-value pair format, you can use string manipulation or regular expressions to parse and create the dictionary. For example,

import json

 and then

my_dict = json.loads(my_string)

if the string is in JSON format.


Source link

اترك تعليقاً

لن يتم نشر عنوان بريدك الإلكتروني. الحقول الإلزامية مشار إليها بـ *

زر الذهاب إلى الأعلى

Please turn off the ad blocker, as ads are the only source of our continuity

برجاء دعمنا عن طريق تعطيل إضافة Adblock