HomepythonDictionaries (dict) and working with them. Dictionary methods in Python

Dictionaries (dict) and working with them. Dictionary methods in Python

Introduction

Dictionaries in Python are a type of data structure that allow you to store data in key-value pairs. They are highly efficient for lookups and are widely used in various applications where quick access to data is required. This article provides an in-depth look at Python dictionaries, including their creation, usage, and the extensive range of methods available to manipulate them.

What is a Dictionary?

A dictionary in Python is an unordered collection of items. Each item is a key-value pair, and the keys must be unique and immutable (such as strings, numbers, or tuples with immutable elements). Values, on the other hand, can be of any data type and can be duplicated.

Basic Dictionary Operations

Creating a Dictionary

You can create a dictionary using curly braces {} or the dict() constructor.

# Using curly braces
person = {
    'name': 'John',
    'age': 30,
    'city': 'New York'
}

# Using the dict() constructor
person = dict(name='John', age=30, city='New York')

Accessing Values

You can access dictionary values by referring to their keys.

print(person['name'])  # Output: John
print(person.get('age'))  # Output: 30

Adding and Modifying Items

You can add new key-value pairs or modify existing ones by assigning values to keys.

person['email'] = 'john.doe@example.com'  # Adding a new key-value pair
person['age'] = 31  # Modifying an existing key-value pair

Removing Items

You can remove items from a dictionary using the del statement, pop(), or popitem().

del person['city']  # Removes the key 'city'
age = person.pop('age')  # Removes and returns the value associated with 'age'
last_item = person.popitem()  # Removes and returns the last inserted key-value pair

Dictionary Methods

Python dictionaries come with a variety of built-in methods that make it easy to perform common operations. Here’s a detailed look at each of these methods.

clear()

Removes all items from the dictionary.

person.clear()
print(person)  # Output: {}

copy()

Returns a shallow copy of the dictionary.

person_copy = person.copy()
print(person_copy)  # Output: {'name': 'John', 'age': 31, 'email': 'john.doe@example.com'}

fromkeys(seq, value)

Creates a new dictionary with keys from seq and values set to value.

keys = ['name', 'age', 'city']
default_person = dict.fromkeys(keys, 'unknown')
print(default_person)  # Output: {'name': 'unknown', 'age': 'unknown', 'city': 'unknown'}

get(key, default)

Returns the value for the specified key if the key is in the dictionary; otherwise, it returns default.

name = person.get('name', 'N/A')
print(name)  # Output: John

items()

Returns a view object that displays a list of dictionary’s key-value tuple pairs.

print(person.items())  # Output: dict_items([('name', 'John'), ('age', 31), ('email', 'john.doe@example.com')])

keys()

Returns a view object that displays a list of all the keys in the dictionary.

print(person.keys())  # Output: dict_keys(['name', 'age', 'email'])

pop(key, default)

Removes the specified key and returns the corresponding value. If the key is not found, default is returned.

email = person.pop('email', 'N/A')
print(email)  # Output: john.doe@example.com

popitem()

Removes and returns the last inserted key-value pair.

last_item = person.popitem()
print(last_item)  # Output: ('email', 'john.doe@example.com')

setdefault(key, default)

Returns the value of the specified key. If the key does not exist, it inserts the key with the specified default value.

age = person.setdefault('age', 0)
print(age)  # Output: 31

update([other])

Updates the dictionary with elements from another dictionary object or from an iterable of key-value pairs.

updates = {'age': 32, 'city': 'New York'}
person.update(updates)
print(person)  # Output: {'name': 'John', 'age': 32, 'city': 'New York'}

values()

Returns a view object that displays a list of all the values in the dictionary.

print(person.values())  # Output: dict_values(['John', 32, 'New York'])

Dictionary Comprehensions

Dictionary comprehensions provide a concise way to create dictionaries. They follow the same syntax as list comprehensions but use curly braces.

squares = {x: x*x for x in range(6)}
print(squares)  # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Subscribe
Notify of

0 Comments
Inline Feedbacks
View all comments

Popular