0% found this document useful (0 votes)
10 views4 pages

Dictonary & Build Methods

The document provides an overview of Python dictionaries, detailing their structure as mutable, unordered collections of key-value pairs. It explains how to create, access, modify, and remove elements, as well as methods for looping through dictionaries and built-in functions like clear(), copy(), and update(). Overall, it emphasizes the flexibility and efficiency of dictionaries in data manipulation.

Uploaded by

rj0110865
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views4 pages

Dictonary & Build Methods

The document provides an overview of Python dictionaries, detailing their structure as mutable, unordered collections of key-value pairs. It explains how to create, access, modify, and remove elements, as well as methods for looping through dictionaries and built-in functions like clear(), copy(), and update(). Overall, it emphasizes the flexibility and efficiency of dictionaries in data manipulation.

Uploaded by

rj0110865
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

In Python, a dictionary is a data structure that stores data in key-value pairs.

Dictionaries are
mutable, unordered, and indexed by keys, which are unique and can be of any hashable type
(typically strings or numbers). The values associated with keys can be of any type.

Creating a Dictionary

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

# Creating a dictionary with curly braces

person = {

"name": "John",

"age": 30,

"city": "New York"

# Creating a dictionary using dict()

person2 = dict(name="Alice", age=25, city="Los Angeles")

Accessing Dictionary Values

To access values in a dictionary, we use the key inside square brackets [] or the .get() method.

# Accessing with square brackets

print(person["name"]) # Output: John

# Accessing with the get() method (prevents KeyError if key doesn't exist)

print(person.get("age")) # Output: 30

print(person.get("gender", "Not specified")) # Output: Not specified (default value)

Adding or Updating Values

we can add a new key-value pair or update an existing key's value.

# Adding a new key-value pair

person["gender"] = "Male"

# Updating an existing key's value

person["age"] = 31

Removing Elements

There are several ways to remove elements from a dictionary:

 pop(key) removes the item with the specified key and returns its value.
 popitem() removes and returns the last inserted item (useful for Python 3.7+ where
dictionaries preserve insertion order).

 del removes the item with the specified key.

 clear() removes all items from the dictionary.

# Using pop() to remove a key

age = person.pop("age") # Removes "age" and returns its value

print(age) # Output: 31

# Using del to remove a key

del person["city"]

# Using clear() to empty the dictionary

person.clear() # Removes all items

Looping Through a Dictionary

You can loop through a dictionary in several ways:

 Looping through the keys.

 Looping through the values.

 Looping through both keys and values.

# Loop through keys

for key in person:

print(key)

# Loop through values

for value in person.values():

print(value)

# Loop through both keys and values

for key, value in person.items():

print(f"{key}: {value}")

Dictionary Methods

 keys() returns a list of all the keys.


 values() returns a list of all the values.

 items() returns a list of key-value pairs as tuples.

 update() merges another dictionary into the current one.

Python dictionaries are powerful and flexible, allowing you to store and manipulate data efficiently
using key-value pairs. Common operations include accessing, adding, updating, and removing
elements, as well as looping through the dictionary.

Build in methods in dictonaries

Python dictionaries come with a variety of built-in methods to manipulate and interact with the data
they store. Below is a list of commonly used dictionary methods in Python, along with examples for
each.

1. dict.clear()

Removes all elements from the dictionary, leaving it empty.

person = {"name": "John", "age": 30, "city": "New York"}

person.clear()

print(person) # Output: {}

2. dict.copy()

Returns a shallow copy of the dictionary.

person = {"name": "John", "age": 30, "city": "New York"}

person_copy = person.copy()

print(person_copy) # Output: {'name': 'John', 'age': 30, 'city': 'New York'}

3. dict.get(key[, default])

Returns the value for the specified key. If the key does not exist, returns the optional default value
(or None if no default is provided).

person = {"name": "John", "age": 30}

print(person.get("age")) # Output: 30

print(person.get("gender", "N/A")) # Output: N/A

4. dict.items()

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

person = {"name": "John", "age": 30}

print(person.items()) # Output: dict_items([('name', 'John'), ('age', 30)])

5. dict.keys()

Returns a view object that displays a list of all the dictionary’s keys.
person = {"name": "John", "age": 30}

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

6. dict.values()

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

person = {"name": "John", "age": 30}

print(person.values()) # Output: dict_values(['John', 30])

7. dict.pop(key[, default])

Removes and returns the value for the specified key. If the key is not found, it returns the optional
default value (or raises a KeyError if no default is provided).

person = {"name": "John", "age": 30}

age = person.pop("age")

print(age) # Output: 30

print(person) # Output: {'name': 'John'}

9. dict.setdefault(key[, default])

If the key exists, it returns its value. If the key doesn’t exist, it inserts the key with the provided
default value and returns the default.

person = {"name": "John"}

age = person.setdefault("age", 25)

print(age) # Output: 25

print(person) # Output: {'name': 'John', 'age': 25}

10. dict.update([other])

Updates the dictionary with elements from another dictionary or iterable of key-value pairs. Existing
keys will be updated, and new ones will be added.

person = {"name": "John", "age": 30}

person.update({"city": "New York", "age": 31})

print(person) # Output: {'name': 'John', 'age': 31, 'city': 'New York'}

11. dict.fromkeys(keys[, value])

Creates a new dictionary from the given sequence of keys, with all values set to the specified value
(or None if no value is provided).

keys = ["name", "age", "city"]

new_dict = dict.fromkeys(keys, "Unknown")

print(new_dict) # Output: {'name': 'Unknown', 'age': 'Unknown', 'city': 'Unknown'}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy