Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Python Dictionary Fundamentals and Operations

Tech 1

Dictionary Creation

Python dictionaries can be initialized using curly braces {} or the dict() constructor:

# Creating an empty dictionary
data = {}

# Adding key-value pairs
data["primary"] = "this is the first item"
data["secondary"] = "this is the second item"
data
{'primary': 'this is the first item', 'secondary': 'this is the second item'}

Key Characteristics

Dictionary keys are unordered. When displaying dictionary contents, Python does not guarantee the order matches insertion sequence since keys lack inherent ordering.

Due to this unordered nature, numeric indexing is not supported for dictionary access. Additionally, using numbers as keys can create confusion with sequential access patterns.

Immutable Keys Requirement

For hashing purposes, dictionary keys must be immutable objects, while values can be any Python object:

fruits = {}
fruits['red'] = ['strawberry', 'cherry', 'apple']
fruits['yellow'] = ['banana', 'lemon']
fruits

Output:

{'red': ['strawberry', 'cherry', 'apple'], 
 'yellow': ['banana', 'lemon']}

Dictionary Initialization with Constructor

inventory = dict([
    ('laptop', 123),
    ('mouse', 456),
    ('keyboard', 789)
])
inventory
{'laptop': 123, 'mouse': 456, 'keyboard': 789}

Suitable Key Types

Among immutable types, integers and string are most commonly used as dictionary keys. Floating-point numbers are generally discouraged due to precision issues that can cause unexpected behavior.

Tuples can also serve as keys since they maintain order. Consequently, ('laptop', 'mouse') and ('mouse', 'laptop') represent distinct keys:

devices = {}
devices[('laptop', 'mouse')] = 100
devices[('mouse', 'laptop')] = 200
print(devices['laptop', 'mouse'])
print(devices['mouse', 'laptop'])
100
200

Dictionary Methods

get Method

Retrieves the value associated with a key, returning a default value (None if unspecified) when the key doesn't exist.

pop Method

devices.pop(('laptop', 'mouse'))
100

update Method

employee = {}
employee['identifier'] = 12
employee['name'] = "Alice"
employee['surname'] = "Smith"
print(employee)
{'identifier': 12, 'name': 'Alice', 'surname': 'Smith'}

Modifying specific fields:

updates = {'identifier': 44, 'name': "Robert"}
employee.update(updates)
print(employee)
{'identifier': 44, 'name': 'Robert', 'surname': 'Smith'}

Membership Testing

'name' in employee
True

keys, values, and items Methods

The keys() method returns a list of all dictionary keys.

The values() method returns all dictionary values.

The items() method returns a list of tuples containing all key-value pairs.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.