0% found this document useful (0 votes)
11 views

Python Dictonary

Python dictionary

Uploaded by

hcblanco17
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Python Dictonary

Python dictionary

Uploaded by

hcblanco17
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

{”Python”: “Dictonary”}

Everything you ever need to know

Your All-in-One Guide to Mastering Dictonary Operations


Introduction

Definition: Dictionaries are unordered,


mutable collections of key-value pairs

Data Types: Keys must be immutable (e.g.,


strings, numbers, tuples), values can be any
type

Usage: Often used for fast lookups and


representing structured data
Creating Dictionaries

Use curly braces {} or the dict() constructor

Examples
Accessing Dictionary Elements
Use square brackets [] with the key to
access values

Use the get() method for safe access


(returns None or a default value if key not
found)

Examples
Modifying Dictionaries
Add or update key-value pairs using
assignment

Use update() method to add multiple key-


value pairs

Examples
Removing Items from Dictionaries
Use del statement to remove a specific key-
value pair

pop() method removes and returns the


value for a given key

clear() method removes all items from the


dictionary

Examples
1. keys()
Returns a view object containing all keys in
the dictionary

Examples
2. values()
Returns a view object containing all values
in the dictionary

Examples
3. items()
Returns a view object containing all key-
value pairs as tuples

Examples
4. get(key[, default])
Returns the value for the given key, or a
default value if the key is not found

Examples
5. pop(key[, default])
Removes and returns the value for the given
key. Raises a KeyError if the key is not
found and no default is provided

Examples
6. popitem()
Removes and returns an arbitrary (key,
value) pair from the dictionary. Raises a
KeyError if the dictionary is empty

Examples
7. update([other])
Updates the dictionary with key-value pairs
from another dictionary or iterable of key-
value pairs

Examples
8. setdefault(key[, default])
Returns the value of the key if it exists,
otherwise inserts the key with the given
default value and returns the default

Examples
9. copy()
Returns a shallow copy of the dictionary

Examples
10. clear()
Removes all items from the dictionary

Examples
Introduction
Dictionary view objects are returned by the
keys(), values(), and items() methods.

They provide a dynamic view of the dictionary's


entries, which means they change as the
dictionary changes

Key features of view objects

Dynamic updates

Support for set operations

Iterable

Length and membership testing


Dynamic updates
Examples
Support for set operations
Examples
Iterable
Examples
Length and membership testing
Examples
1. len(dict)
Returns the number of key-value pairs in the
dictionary

Examples
2. sorted(dict)
Returns a new sorted list of keys from the
dictionary

Examples
3. any(dict)
Returns True if any key in the dictionary is
True (non-zero, non-empty, or True)

Examples
4. all(dict)
Returns True if all keys in the dictionary are
True (non-zero, non-empty, or True)

Examples
5. dict()
Creates a new dictionary. Can be used to
create dictionaries from various input types

Examples
1. Caching and Memoization
Dictionaries are excellent for storing
computed results to avoid redundant
calculations

Examples
2. Configuration Settings
Store application settings as key-value pairs
for easy access and modification

Examples
3. JSON-like Data Structures
Represent structured data in a human-
readable format, often used for API
responses or configuration files

Examples
4. Frequency Counting
Count occurrences of items in a collection
efficiently

Examples
5. Graph Representations
Represent adjacency lists for graph
algorithms

Examples
6. Lookup Tables
Create efficient mappings for quick data
retrieval

Examples
1. Default Dictionaries
(collections.defaultdict)
Automatically initializes new keys with a
default value

Examples
2. Ordered Dictionaries
(collections.OrderedDict)
Remembers the order in which keys were
inserted

Examples
3. Counter Dictionaries
(collections.Counter)
Specialized dictionary for counting
hashable objects

Examples
4. Dictionary Merging (Python
3.9+)
Use the | operator to merge dictionaries

Examples
Key Errors: Use get() or setdefault() to
avoid KeyError exceptions

Mutable Keys: Don't use mutable objects


(like lists) as dictionary keys

Memory Usage: Be cautious with large


dictionaries, as they can consume
significant memory

Default Values: Use dict.get(key, default)


instead of checking if key in dict

Copying: Use dict.copy() for shallow copies


or copy.deepcopy() for deep copies

Key Existence: Use in operator to check for


key existence instead of exceptions
Common Errors:

KeyError: Occurs when trying to access a


non-existent key

TypeError: Unhashable type (e.g., using a


list as a key)

Debugging Tips:

Use print() to inspect dictionary contents

Utilize the in operator to check for key


existence before accessing

Use pprint module for pretty-printing


complex dictionaries
1. Dictionaries vs Lists

Dictionaries have O(1) average-case lookup,


lists have O(n)

Dictionaries are unordered (before Python


3.7), lists are ordered

Use dictionaries when you need fast


lookups by key

2. Dictionaries vs Sets

Both have fast lookups, but dictionaries


store key-value pairs

Use sets for membership testing,


dictionaries for associating values with
keys
3. Dictionaries vs Tuples

Dictionaries are mutable and use keys for


access, tuples are immutable and use
indices

Use dictionaries for named access to


elements, tuples for fixed collections
1. Word Frequency Analyzer

Build a program that counts word


frequencies in a given text using
dictionaries

2. Configuration Parser

Create a program that reads and writes


configuration files using dictionaries

3. Contact Book Application

Create a dictionary-based contact book


with functions to add, update, delete, and
search contacts
Naresh Saginala Agile Coach

Repost
If you
find
this
helpful

@nareshsaginala

You might also like